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.
Asked
Active
Viewed 293 times
1
-
Apply chain of responsibility pattern here – Mạnh Quyết Nguyễn Jun 13 '19 at 05:34
-
2You can look into this solution https://stackoverflow.com/questions/4024544/how-to-parse-dates-in-multiple-formats-using-simpledateformat – Shivam Pandey Jun 13 '19 at 05:36
-
You can really think of considering solution of @MạnhQuyếtNguyễn. However, you can also check if string length is 4 then you need to parse the date else you can use standard format. – Aniket Kulkarni Jun 13 '19 at 05:46
-
1How can you figure out a unix timestamp just from a year? Do you just want to get the time at 1 Jan 00:00 of that year? – Sweeper Jun 13 '19 at 05:50
-
@Sweeper I assume they expect me to do exactly what you said, get the time at 1 Jan 00:00. – someone_smarter Jun 13 '19 at 05:54
-
*get the time at 1 Jan 00:00* You will need to decide on a time zone for that too. – Ole V.V. Jun 13 '19 at 13:44
1 Answers
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