How can I get the following format:
2015-01-31T00:00:00Z
(ISO8601 GMT date format)
Out of a DateTime object in joda time (java) ? Eg.
DateTime time = DateTime.now(); String str = // Get something like 2012-02-07T00:00:00Z
Thanks! :)
The Date/Time API in Java works with the ISO 8601 format by default, which is (yyyy-MM-dd) . All Dates by default follow this format, and all Strings that are converted must follow it if you're using the default formatter.
Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java. util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java.
To create a datetime object representing a specific date and time, you may use an initialization string: DateTime dt = new DateTime("2004-12-13T21:39:45.618-08:00"); The initialization string must be in a format that is compatible with the ISO8601 standard.
How to change the SimpleDateFormat to jodatime? String s = "2014-01-15T14:23:50.026"; DateTimeFormatter dtf = DateTimeFormat. forPattern("yyyy-MM-dd'T'HH:mm:ss. SSSS"); DateTime instant = dtf.
The JODA Javadoc indicates that toString
for DateTime
outputs the date in ISO8601. If you need to have all of the time fields zeroed out, do this:
final DateTime today = new DateTime().withTime(0, 0, 0, 0); System.out.println(today);
That will include milliseconds in the output string. To get rid of them you would need to use the formatter that @jgm suggests here.
If you want it to match the format you are asking for in this post (with the literal Z
character) this would work:
System.out.println(today.toString(DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")));
If you need the value to be UTC, initialize it like this:
final DateTime today = new DateTime().withZone(DateTimeZone.UTC).withTime(0, 0, 0, 0);
@jgm In the document, ISODateTimeFormat.dateTime()
is described
Returns a formatter that combines a full date and time, separated by a 'T' (yyyy-MM-dd'T'HH:mm:ss.SSSZZ).
but if you set the timezone, e.g.,
DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); System.out.println(fmt.print(new DateTime().toDateTime(DateTimeZone.UTC)));
it will ends in Z.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With