Parse an ISO8601 date string to date with UTC time

I am trying to serialize / deserialize a date from / to a javascript application.

On the server side, I use java, JodaTime is installed on it. I have learned how to serialize an ISO with a UTC timezone, but cannot find out how to perform the reverse operation.

Here is my code

public static String getIsoDate( Date date ) { SimpleDateFormat dateToIsoDateString = new SimpleDateFormat( ISO_8601_DATE_FORMAT ); TimeZone tz = TimeZone.getTimeZone("UTC"); dateToIsoDateString.setTimeZone( tz ); return dateToIsoDateString.format( date ); } // this will return a date with GMT timezone public static Date getDateFromIsoDateString( String iso8601date ) { DateTimeFormatter jodaParser = ISODateTimeFormat.dateTimeNoMillis(); return jodaParser.parseDateTime( iso8601date ).toDate(); } 

I don’t mind using or not Joda, I just need a quick and effective solution,

thanks

+6
source share
2 answers

If you are using Java 7 or earlier, you can refer to this post.

If you are using Java 8, you can do:

  DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_DATE_TIME; TemporalAccessor accessor = timeFormatter.parse("2015-10-27T16:22:27.605-07:00"); Date date = Date.from(Instant.from(accessor)); System.out.println(date); 
+16
source

Your question is incomprehensible and specific. Perhaps these little examples will help. Mixing the old java.util.Date and .Calendar classes with Joda-Time can be confusing. Joda-Time completely replaces these classes, not additions.

Joda-Time by default uses ISO 8601 for strings, both for parsing and for generating. Joda-Time has built-in default parsers for ISO 8601, so just pass your compatible string to the constructor or static parse method.

 java.util.Date date = new DateTime( "2010-01-01T12:00:00+01:00Z" ).toDate(); 

If possible, avoid java.util.Date and .Calendar and stick with Joda-Time , and these are classes like DateTime . Use .Date only where required for other classes.

 DateTime dateTimeUtc = new DateTime( someJavaDotUtilDotDate, DateTimeZone.UTC ); // Joda-Time can convert from java.util.Date type which has no time zone. String output = dateTime.toString(); // Defaults to ISO 8601 format. DateTime dateTimeUtc2 = new DateTime( output, DateTimeZone.UTC ); // Joda-Time can parse ISO 8601 strings. 

For the presentation, set the time zone expected by the user.

 DateTime dateTimeMontréal = dateTimeUtc.withZone( DateTimeZone.forID( "America/Montreal" ) ); 
+3
source

Source: https://habr.com/ru/post/975547/


All Articles