-2

How can I create a date and time string with the timestamp 1420432787 which is equal to 1/05/2015 10:09:47.

Bellow code is also not working

 Date date = new Date(1420432787);
 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:a");
 System.out.println(simpleDateFormat.format(date));

result of this 1/17/1970 10:34 AM

Rathore
  • 1,926
  • 3
  • 19
  • 29

1 Answers1

5

The Date constructor accepts the time as long in milliseconds, not seconds.

You need to multiply it by 1000 and make sure that you supply it as long.

Date date = new Date(timeInSeconds * 1000);

then you can parse it into your date format

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:a");
System.out.println(simpleDateFormat.format(date));
Prasad Khode
  • 6,602
  • 11
  • 44
  • 59
  • I have tried with new Date(timeInSeconds * 1000) but still geting wrong output and my timeInSeconds var in sec. – Rathore Jan 05 '15 at 12:05
  • 1
    @Rathore timeInSeconds should be a long variable, if you want to use the seconds directly then you can 'write Date date = new Date(1420432787L * 1000)' – Prasad Khode Jan 05 '15 at 12:08