I am trying to create a String in a format like 2015-08-20T08:26:21.000Z
I know it can be done with some String splitting techniques, but i am wondering if there is an elegant solution for that (with minimal code changes).
Both of the above are time strings, the final one which i need is Date in ISO 8601 . http://tools.ietf.org/html/rfc3339#section-5.6
I have tried a few similar questions like converting a date string into milliseconds in java but they dont actually solve the purpose.
Also tried using :
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
String nowAsString = df.format(new Date());
Instant.parse( "2015-08-20T08:26:21.000Z" ) .toString()
If all you want to do is eliminate the
.000, then use date-time objects to parse your input string value, then generate a new string representation of that date-time value in a different format.
By the way, if that is your goal, the Question’s title make no sense as both strings mentioned in the first sentence are valid ISO 8601 formatted strings.
Java 8 and later has the new java.time package. These new classes supplant the old java.util.Date/.Calendar & java.text.SimpleDateFormat classes. Those old classes were confusing, troublesome, and flawed.
If all you want is UTC time zone, then you can use the
Instant class. This class represents a point along the timeline without regard to any particular time zone (basically UTC).
Calling an Instant’s
toString generates a String representation of the date-time value using a
DateTimeFormatter.ISO_INSTANT formatter instance. This formatter is automatically flexible about the fractional second. If the value has a whole second, no decimal places are generated (apparently what the Question wants). For a fractional second, digits appear in groups of 3, 6, or 9, as needed to represent the value up to nanosecond resolution. Note: this format may exceed ISO 8601 limit of milliseconds (3 decimal places).
Here is some example code in Java 8 Update 51.
String output = Instant.parse( "2015-08-20T08:26:21.000Z" ).toString( ); System.out.println("output: " + output );
Changing to a fractional second,
String output = Instant.parse( "2015-08-20T08:26:21.08Z" ).toString( );
If interested in any time zone other than UTC, then make a
ZonedDateTime object from that
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , ZoneId.of( "America/Montreal" ) ) ;