-1

I am receiving the date as "1279340983" so I want to convert to readable format like 2010-07-17. I have tried using following code

String createdTime = "1279340983";
Date date1 = new Date(Long.parseLong(createdTime));
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf1.format(date1));

but it returns 1970-01-16as output. when tried to online tool it is showing Sat, 17 Jul 2010 04:29:43 GMT any idea why this code not showing intended output ?

SrinivasDJ
  • 319
  • 1
  • 5
  • 10

2 Answers2

2

in your given time does not has time zone included so the Java will take local time zone,

    String createdTime = "1279340983";
    Date date1 = new Date(Long.parseLong(createdTime) * 1000); // right here
    System.out.println(date1.toString()); // this is what you are looking online
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss zzz"); // here you would have to customize the output format you are looking for
    System.out.println(sdf1.format(date1));

output

Sat Jul 17 09:59:43 IST 2010 // this would be your online result 
2010-07-17 09:59:43 IST      // this is something you want to change ,

you might want to change the time zone should you like to have that

sdf1.setTimeZone(TimeZone.getTimeZone("GMT"));

output 2010-07-17 04:29:43 GMT

Pankaj Nimgade
  • 4,529
  • 3
  • 20
  • 30
0

The online converter you're using is converting date from seconds. Java's Date constructor uses milliseconds, not seconds. You need to multiply your answer by 1000 to make it match.

    String createdTime = "1279340983";
    Date date1 = new Date(Long.parseLong(createdTime) * 1000); // right here
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(sdf1.format(date1));
Tah
  • 1,526
  • 14
  • 22