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!
Asked
Active
Viewed 9,147 times
1
-
1do you think using `SimpleDateFormat` is not a straight forward way? – singhakash May 08 '15 at 12:38
-
What exactly do you mean with "timestamp field"? A column in a database table? An input field (e.g. `JTextField`) in your Swing application? A form element in your HTML page? – May 08 '15 at 12:40
-
Possible duplicate of http://stackoverflow.com/questions/1459656/how-to-get-the-current-time-in-yyyy-mm-dd-hhmisec-millisecond-format-in-java – akhil_mittal May 08 '15 at 12:42
-
Keep in mind, dates or timestamps does NOT have a format. So, your question should be: "How to get a `java.sql.Timestamp` in `MM-dd-yyyy hh:mm:ss` format" – Albert May 08 '15 at 12:47
4 Answers
3
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));

Jordi Castilla
- 26,609
- 8
- 70
- 109
1
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

Abubakkar
- 15,488
- 8
- 55
- 83
1
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());
}

Shamil
- 95
- 2
- 7
0
Try like this using SimpleDateFormat:
DateFormat d = new SimpleDateFormat("MM-dd-yyyy HH:mm");
String str= d.format(timestamp);
System.out.println(str);

Rahul Tripathi
- 168,305
- 31
- 280
- 331