Is there an easy way to convert a timestamp field which is of format yyyy-MM-dd hh:mm:ss
to a String of format MM-dd-yyyy hh:mm:ss
. I was able to do so using substr but was wondering if there is a straighforward way of converting it. Thanks!
First of all... Date
or Timestamp
objects have it's own format , so you don't have to care how is stored, you need to change the format in the moment you show it, but not when you store it :
When you need to show/print it use SimpleDateFormat
for example if you want to show Timestamp
in own format ( MM-dd-yyyy hh:mm:ss
) you must do like this:
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
System.out.println("My date formatted is: " + sdf.format(timestamp));
You can use SimpleDateFormat
.
Example :
SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date d = input.parse("your date string goes here");
SimpleDateFormat output = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
System.out.println(output.format(d)); // will return date as string in format MM-dd-yyyy hh:mm:ss
private static String format(Date sourceDate) throws ParseException {
SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(sourceDate));
return dateTimeFormat.format(calendar.getTime());
}
Try like this using SimpleDateFormat :
DateFormat d = new SimpleDateFormat("MM-dd-yyyy HH:mm");
String str= d.format(timestamp);
System.out.println(str);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.