0

I am trying to convert numeric string value in to date.

My code is

String input =  "1537011000";
Date d = new SimpleDateFormat("ddMMMM").parse(input);
String output = new SimpleDateFormat("MMMM dd, yyyy").format(d);
System.out.println("output = " + output);

**but I'm not able to convert. I'm getting an Exception: Unparseable date: "1537011000"

Expected result is 15th September

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • What does "1537011000" stand for? Number of (milli)seconds since some starting point? Look like seconds (and not milliseconds) since 01/01/1970 – Robert Kock Sep 14 '18 at 09:56
  • I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Sep 14 '18 at 10:30

3 Answers3

2

You seem to have Epoch seconds in your value, so you can use new Date(long) using the long representation of that value times 1000:

Date d = new Date(Long.parseLong(input) * 1000);

That sets d to Sep 15th

ernest_k
  • 44,416
  • 5
  • 53
  • 99
1

SimpleDateFormat("ddMMMM").parse(input) parses a string input which should contain a date formatted in a given format, in your case "ddMMMM". So it expects something like "18Sept" (where 18 is a year) and not the Epoch time. You have to convert the epoch time into data and then print it in a desired format.

Psytho
  • 3,313
  • 2
  • 19
  • 27
1

It is the number of seconds, Date uses ms. And the new date time classes (LocalDateTime) should be the prefered way.

    LocalDateTime t = LocalDateTime.ofEpochSecond(1537011000L, 0, ZoneOffset.UTC);
    Date d = new Date(1537011000L*1000);
    System.out.println(t);
    System.out.println(d);

2018-09-15T11:30
Sat Sep 15 13:30:00 CEST 2018
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • 1
    Or simpler yet: `Instant.ofEpochSecond(1_537_011_000)`; also preserves the offset information (and better to avoid the outdated and poorly designed `Date` class if possible). – Ole V.V. Sep 14 '18 at 10:34
  • @OleV.V. `Instant.ofEpochSecond` was my first thought also; indeed cleanest, though requires more overview, insight into using the many classes. `Date` was mentioned by the OP so s/ms problem mentioned. – Joop Eggen Sep 14 '18 at 11:34