1

I get list of objects from Json, each of them includes date String. There are two different formats, one is standard "yyyy-MM-dd" format, second is just year "yyyy". What is the elegant way to parse these string to unix timestamp? At the moment i am using double try-catch block with SimpleDateFormat but i would like to find better solution.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161

1 Answers1

1

If the length is four characters long, parse as a Year.

Year y = Year.parse( input ) ;

How do you want to represent that as a moment? Perhaps first moment of first day of the year, in UTC?

LocalDate ld = y.atDay( 1 ) ;
Instant instant = ld.atStartOfDay( ZoneOffset.UTC ).toInstant() ;

By “Unix timestamp” did you mean a count of milliseconds since the first moment of 1970 in UTC?

long millis = instant.toEpochMilli() ;

If the input is 10 characters long, parse as a LocalDate.

LocalDate ld = LocalDate.parse( input ) ;

The do the same as seen above.

long millis = ld.atStartOfDay( ZoneOffset.UTC ).toInstant().toEpochMilli() ;

Put that all together.

switch ( input.length() ) {
    case 4 : return Year.parse( input ).atDay( 1 ).atStartOfDay( ZoneOffset.UTC ).toInstant().toEpochMilli() ;
    case 10 : return LocalDate.parse( input ).atStartOfDay( ZoneOffset.UTC ).toInstant().toEpochMilli() ;
    default : … throw exception, unexpected input. 
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154