-4

I have to convert datetime from one format to another in java. Here is the period im starting with:

2001-01-01T01:00Z/2002-02-02T02:00Z

and here is the result i need to end up with:

2002-02-02T02:00:00

So basically i need the second part of the period and i need to add :00 as seconds to the end and remove the Z.

Im not really familiar with date formats. Is one of these a standard format? Can i use some kind of library to read and convert these datetimes?

azro
  • 53,056
  • 7
  • 34
  • 70
user1985273
  • 1,817
  • 15
  • 50
  • 85

1 Answers1

1

tl;dr

Interval.parse( input ) 
        .getEnd()
        .atOffset( ZoneOffset.UTC ) 
        .format(
            DateTimeFormatter.ISO_LOCAL_DATE_TIME 
        )

Interval

Your input string for the period is on standard ISO 8601 format. It represents a pair of moments, where the Z on the end is short for Zulu and means UTC. The slash character separates the start and stop.

Parse those with the Interval class found in the ThreeTen-Extra project.

Interval interval = Interval.parse( input ) ;

Instant

Extract the stop moment.

Instant instant = interval.getEnd() ;

OffsetDateTime

I suspect you should be working with objects like Instant rather than manipulating the String. But if you insist, for generating a formatted string, convert the Instant to a OffsetDateTime.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;

Also, it is usually a bad idea to drop the offset/zone indicator such as the Z. The resulting string becomes ambiguous as to its meaning, no longer representing a specific moment on the timeline. But if you insist, there is a predefined for matter.

String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154