Question

Im having field type java.util.date and from it im getting the value of to.string() Sat Sep 14 00:00:00 IDT 2013 but I need to get it in different format which is EDM format like 2013-09-12T14:00 . There is simple way to do that?

Thanks!

Était-ce utile?

La solution

Use SimpleDateFormat (a good tutorial is available here). Consider this example:

Date date = new Date();
System.out.println(date);

which outputs:

Mon Jun 24 21:46:22 BST 2013

To convert to EDM format, do the following:

String firstPartOfPattern = "yyyy-MM-dd";
String secondPartOfPattern = "HH:mm:ss";
SimpleDateFormat sdf1 = new SimpleDateFormat(firstPartOfPattern);
SimpleDateFormat sdf2 = new SimpleDateFormat(secondPartOfPattern);
String formattedDate = sdf1.format(date) + "T" + sdf2.format(date);

formattedDate now has the following format:

2013-06-24T21:46:22

Autres conseils

tl;dr

myUtilDate.toInstant().toString()

2017-01-23T01:23:45.123Z

ISO 8601

Your desired format is defined in the ISO 8601 standard.

The java.time classes use ISO 8601 formats by default when parsing or generating strings.

java.time

Avoid using the outdated troublesome old date-time classes such as Date that are now legacy, supplanted by the java.time classes.

Convert your Date object to java.time by using new methods added to the old classes. The modern counterpart to Date is Instant for a moment on the timeline in UTC but with a finer resolution of nanoseconds rather than milliseconds.

Instant instant = myUtilDate.toInstant() ;

To generate your ISO 8601 string, simply call toString. The Z on the end is short for Zulu and means UTC.

String output = instant.toString() ;

Edit: As mentioned you shouldn't use SimpleDateFormat anymore in Java 8+!

You can do also simplify the steps described by Sam:

String pattern = "yyyy-MM-dd'T'HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String formattedDate = sdf.format(date);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top