el323
el323

Reputation: 2920

Convert days from epoch to date

I want to convert number of days since epoch to a date. Let's say I have the following Timestamp in days: 17749 then it should be converted to Monday Aug 06 2018.

I am trying using the following code:

Date date = new SimpleDateFormat("D").parse(String.valueOf("17749"));
System.out.println(date);

But I am getting Sun Aug 05 00:00:00 PKT 2018. The date is one day earlier than what it should be and how can I convert it to yyyy-mm-dd?

Upvotes: 1

Views: 6427

Answers (2)

azro
azro

Reputation: 54148

Using the latest API java.time you may use :

  • the static method ofEpochDay:

    LocalDate d = LocalDate.ofEpochDay(17749);
    System.out.println(d);                       // 2018-08-06
    
  • the static constant EPOCH :

    LocalDate.EPOCH.plusDays(17749);
    

Then for the output, it's only String, so you can use built-in formatter or create yours : DateTimeFormatter

Upvotes: 7

T.J. Crowder
T.J. Crowder

Reputation: 1074335

D in a SimpleDateFormat pattern is the day of the year, not days since The Epoch.

The simplest thing is probably to multiply by the number of milliseconds in a day (86400000 = 24 * 60 * 60 * 1000) and use new Date(milliseconds):

long days = 17749;
Date d = new Date(days * 86400000L);

The old java.util.Date is a failed API, though. You might look at java.time.LocalDate (or one of the other java.time classes), for instance, which has plusDays and a handy EPOCH static:

// ACTUALLY, THERE'S A BETTER WAY THAN THIS, SEE LINK AFTER CODE BLOCK
long days = 17749;
LocalDate d = LocalDate.EPOCH.plusDays(days);

(Ah, I missed ofEpochDay, see azro's answer.)

Upvotes: 2

Related Questions