-4

I have to extract date in the format MM-dd-yyyy in java from the since time value. Since time is the time at which the doucment is created. For example, if since time is 1452413972759, date would be "Sun, 10 Jan 2016 08:19:32 GMT" (Calculated from http://www.epochconverter.com/) . From this, I could get date in desired format but I am unable to code for the first step i.e., converting since time to date. Can someone help me?

I tried

DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
        java.util.Date date = df.parse("1452320105343");
        String DATE_FORMAT = "MM/dd/yyyy";
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        System.out.println("Today is " + sdf.format(date));

But it gives parse exception.

Sanjay
  • 443
  • 1
  • 7
  • 22
  • 1
    Simply: `java.util.Date date = new Date(1452320105343);`. Note, however, that month, day and year are timezone-dependent, so you need to make sure you are doing the conversion in the appropriate timezone. – Andy Turner Feb 04 '16 at 10:11
  • @AndyTurner. java.util.Date date = new Date(1452320105343); giving The literal 1452320105343 of type int is out of range compile time error. – Sanjay Feb 04 '16 at 10:14
  • Chuck a `L` on the end of the literal to indicate it is a long. – Andy Turner Feb 04 '16 at 10:15

1 Answers1

0

Your code can't work because you're trying to parse a number of milliseconds as if it was a MM/dd/yyyy formatted date.

I would have expected the following code to work, where S represents milliseconds :

DateFormat df = new SimpleDateFormat("S");
java.util.Date date = df.parse("1452413972759");
String DATE_FORMAT = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Today is " + sdf.format(date));

However it doesn't for some reason, displaying a date in the 1970 year.

Instead, the following code that parses seconds rather than milliseconds works for your needs :

DateFormat df = new SimpleDateFormat("s");
java.util.Date date = df.parse("1452413972");  // just remove the last 3 digits, or divide by 1000
String DATE_FORMAT = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Today is " + sdf.format(date));

Or just follow the link from @mohammedkhan and use Date constructor rather than parsing a string :

java.util.Date date = new Date(1452413972759l);
String DATE_FORMAT = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Today is " + sdf.format(date));
Aaron
  • 24,009
  • 2
  • 33
  • 57