1

I am trying to convert java.sql.Date to Days and convert the Days back to java.sql.Date all in UTC but I believe I am off by one day.

I tried below my millis1 and millis2 are off by one day.

import java.sql.Date;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;

public class TestDate {
    public static void main(String... args) {
        String str="2015-03-31";
        Date date=Date.valueOf(str);
        long millis1 = date.getTime();
        System.out.println(millis1);
        int days = getDaysFromDate(date);
        long millis2 = getDateFromDays(days).getTime();
        System.out.println(millis2);
    }

    public static int getDaysFromDate(Date date) {
        return (int)ChronoUnit.DAYS.between(Instant.EPOCH, Instant.ofEpochMilli(date.getTime()));
    }

    public static Date getDateFromDays(int daysSinceEpoch) {
        return new Date(TimeUnit.DAYS.toMillis(daysSinceEpoch));
    }
}
user1870400
  • 6,028
  • 13
  • 54
  • 115

1 Answers1

0

When converting from milliseconds to days, and then converting back to milliseconds from days, you will lose data.

In your case millis1 and millis2 both equal the same amount of DAYS (16525), but millis2 will have fewer milliseconds after the method calls because it doesn't take in account for the extra hours that were not counted as a DAY. The extra hours most likely came from leap years. When using ChronoUnit.DAYS the date should be equivalent at mid-day.

Hayes Roach
  • 121
  • 10