Home > Software design >  UTC formatted string to UTC Date Object using SimpleDateFormat
UTC formatted string to UTC Date Object using SimpleDateFormat

Time:06-27

I have a UTC formatted DateTime String

and need this String to be converted to DATE Object without any Format change.

Currently, when I try to convert it to a date Object it is returned as GMT formatted Date object as depicted in the image attached below.

I have a limitation of using SimpleDateFormat as I have to support API<21 also.

String newDateString = "2022-06-27 08:27:00 UTC";
DateFormat format = new SimpleDateFormat(Constants.EnumDateFormats.DATE_FORMAT7);//"yyyy-MM-dd HH:mm:ss 'UTC'"
                format.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
                Date date = format.parse(newDateString);
                System.out.println(date);//printing GMT formatted Date object but I need Date object in UTC format like 2022-06-27 08:27:00 UTC

I have attached debugged code image image for better under standing.

CodePudding user response:

I have a UTC formatted DateTime String

No, you don’t.

UTC is the prime meridian commonly used for time-keeping. Time zones towards the east use an offset some number of hours-minutes-seconds ahead of UTC; those to the west, behind UTC.

UTC has nothing to do with text formats.

need this String to be converted to DATE Object without any Format change.

There are two Date classes in Java. You should specify which you intended.

And, both classes are terrible, flawed by poor design decisions. They were years ago supplanted by the modern java.time classes defined in JSR 310.

I have a limitation of using SimpleDateFormat as I have to support API<21 also.

Nope, no such limitation. The latest tooling brings most of the java.time functionality to earlier Android, via “API de-sugaring”.

To parse, use DateTimeFormatter to define a matching formatting pattern. Try the following, but I’ve not yet tested.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-d HH:mm:ss OOOO" ).withLocale( Locale.US ) ; 
OffsetDateTime odt = OffsetDateTime.parse( input , f ) ;

Tip: Educate the publisher of your data about the ISO 8601 standard for formatting textual representations of date-time values.


All of this has been covered many times already on Stack Overflow. Please search before posting here.

  • Related