0

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?

el323
  • 2,760
  • 10
  • 45
  • 80
  • Possible duplicate of [Change date format in a Java string](https://stackoverflow.com/questions/4772425/change-date-format-in-a-java-string) –  Aug 06 '18 at 13:41

2 Answers2

5

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

azro
  • 53,056
  • 7
  • 34
  • 70
2

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.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • We should stop teaching to use old Date, and better use new time API. – azro Aug 06 '18 at 13:43
  • @azro - Yes, it is better to use the new API. But since the OP is using `Date`, that's what I used. – T.J. Crowder Aug 06 '18 at 13:43
  • 1
    They all says 'date' as it's the common word, but mostly they just don't know that Date is outdated and that a new API exists – azro Aug 06 '18 at 13:44
  • @azro - Note the code sample in the question, which uses `Date`, specifically. I did add a note about `java.time`, though. – T.J. Crowder Aug 06 '18 at 13:48