Jakub Vlček
Jakub Vlček

Reputation: 1

Parsing and formating date from a different timezone

I have a string in this format: 2021-10-22T21:43:00-05:00 I understand that it is in timezone -5:00 from UTC. Now I want to get the string in UTC with format dd:MMM:yyyy so I can compare it to response from other service. Can you help me with the code so far I am not able to parse it because I am not familiar with the format of the date. Timezone part particularly. I tried

def date = '2021-10-22T21:43:00-05:00'
def timezone = TimeZone.getTimeZone("UTC");
def dateFormat = 'dd:MMM:yyyy'
Date.parse('yyyy-MM-dd',date.take(10)).format(dateFormat,timezone)

problem with this is that I lose the timezone part of the date so I cannot change it. I am using Groovy in ReadyApi software. I am not the most advanced coder so please help. Thanks for answers. :)

Upvotes: 0

Views: 85

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 339787

tl;dr

OffsetDateTime
.parse( "2021-10-22T21:43:00-05:00" )
.toLocalDate()
.isEqual(
    LocalDate
    .parse( 
        "23:Jan:2023" , 
        DateTimeFormatter
        .ofPattern( "dd:MMM:uuuu" )
        .withLocale( Locale.US )
    )
)

Details

I have a string in this format: 2021-10-22T21:43:00-05:00 I understand that it is in timezone -5:00 from UTC.

No, that is not a time zone. That is an offset from UTC, a number of hours-minutes-seconds ahead or behind the temporal prime meridian of UTC.

A time zone is much more. A time zone is a named history of the past, present, and future changes to the offset used by the people of a particular region as decided by their politicians. A time zone has a name in format of Continent/Region such as Europe/Paris. See list.

Parse your input as a OffsetDateTime. Here is some code in Java syntax as I’ve not yet learned Groovy.

Your input string complies with the ISO 8601 standard format used by default in the java.time classes. So no need to define a formatting pattern.

String input = "2021-10-22T21:43:00-05:00" ;
OffsetDateTime odt = OffsetDateTime.parse( input ) ;

Apparently you want to use the date portion of that value to generate text in the format of dd:MMM:yyyy.

That’s a rather funky format, I must say. You might want to educate the publisher of that data about the benefits of using only ISO 8601 formats.

Define a formatting pattern. Specify a locale to use in localizing the abbreviated name of the month in the middle.

Locale locale = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd:MMM:uuuu" ).withLocale( locale ) ;

Generate text.

String output = odt.format( f ) ;

But if your goal is comparing, I suggest you parse the other string rather than generate text for comparison.

LocalDate target = LocalDate.parse( "23:Jan:2023" , f ) ;

Extract the date portion from our OffsetDateTime object, odt.

LocalDate ld = odt.toLocalDate() ;

Compare.

boolean sameDate = ld.isEqual( target ) ;

Upvotes: 2

Related Questions