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.
  • 76,217
  • 14
  • 120
  • 142

2 Answers2

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
  • 262,936
  • 84
  • 758
  • 1,028
0

This answer is a copy of my answer to another question. Your question may be duplicate of that one: How to convert String to Date without knowing the format?

I once had a task to write a code that would parse a String to date where date format was not known in advance. I.e. I had to parse any valid date format. I wrote a project and after that I wrote an article that described the idea behind my implementation. Here is the link to the article: Java 8 java.time package: parsing any string to date. General Idea is to write all the patterns that you wish to support into external properties file and read them from there and try to parse your String by those formats one by one until you succeed or run out of formats. Note that the order also would be important as some Strings may be valid for several formats (US/European differences). Advantage is that you can keep adding/removing formats to the file without changing your code. So such project could also be customized for different customers

Michael Gantman
  • 5,975
  • 1
  • 17
  • 34