Some of the data I work with sends dates in epoch or unix time. This works fine for software, but it is often helpful to convert those numbers to year, month, and day values for human consumption.
Consider the epoch time value: 1608552000.000 (the decimal places being for milliseconds)
Epoch Converter converts this value to: December 21, 2020 12:00:00 PM (GMT)
In Java, I might write code like this to convert the value:
import java.time.*;
import java.time.format.DateTimeFormatter;
class MyApplication{
public static void main(String[] args){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("YYYY-MM-dd");
String uTime = "1608552000.000";
Float fTime = Float.parseFloat(uTime);
String sTime = LocalDateTime.ofInstant(Instant.ofEpochMilli((long) (fTime*1000)), ZoneOffset.ofHours(-5)).format(dtf);
System.out.println(sTime);
}
}
This code writes out the date: 2020-12-21
Job well done, right? Not so fast.
Consider this epoch value: 1609070400.000
Epoch Converter converts this value to: December 27, 2020 12:00:00 PM (GMT)
However, when I run this number through the code above, the output is: 2021-12-27
The year is wrong! What’s going on here? Well, it turns out the problem is with the date formatting pattern (line 7). In the code, I’m using “Y” (capital Y) to convert the year. The documentation defines this format as a “week-based-year”. December 27 was a Sunday. The first day of 2021 was the following Friday. My best guess is that, since part of that week changed to the year 2021, use of that particular format pattern must apply the year 2021 to all days in the week. Interesting.
Thankfully, if you want to get the actual year for that date, just use “y” (lowercase y). In code, that looks like this:
import java.time.*;
import java.time.format.DateTimeFormatter;
class MyApplication{
public static void main(String[] args){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String uTime = "1609070400.000";
Float fTime = Float.parseFloat(uTime);
String sTime = LocalDateTime.ofInstant(Instant.ofEpochMilli((long) (fTime*1000)), ZoneOffset.ofHours(-5)).format(dtf);
System.out.println(sTime);
}
}
And now the output is as I expect: 2020-12-27
Recent Comments