wazza
wazza

Reputation: 800

Timestamp conversion in java

I am converting timestamp to date format yyyy-MM-dd HH:mm:ss.SSS and I am using America/New_York as TimeZone. Whenever I convert the timestamp into the date it shows one hour less than usual date and time. How to resolve this in java?

Here's the code:

  String timestamp = "1431941838000";
  long time = Long.valueOf(timestamp);
  Date currentDate = new Date(time);
  DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

  TimeZone zone = TimeZone.getTimeZone("America/New_York");
  df.setTimeZone(zone);
  String finale = df.format(currentDate);

Upvotes: 0

Views: 866

Answers (2)

Balicanta
Balicanta

Reputation: 109

Try to using EST to replace America/New_York like

TimeZone zone = TimeZone.getTimeZone("EST");

Updated

It's My Test code:

    String timestamp = "1431941838000";
    long time = Long.valueOf(timestamp);
    Date currentDate = new Date(time);
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    TimeZone zoneNewYork = TimeZone.getTimeZone("America/New_York");
    df.setTimeZone(zoneNewYork);
    String finale = df.format(currentDate);
    System.out.println(finale);

    TimeZone zoneEst = TimeZone.getTimeZone("EST");
    df.setTimeZone(zoneEst);
    finale = df.format(currentDate);
    System.out.println(finale);

And My result as bellow:

    2015-05-18 05:37:18.000
    2015-05-18 04:37:18.000

Upvotes: 1

Jordi Castilla
Jordi Castilla

Reputation: 26961

You have an extra point in this line:

TimeZone zone = TimeZone.getTimeZone("America/New_York").;
//                                                      ^ here!!!

UPDATE
if you dont get any error, the output must be the correct: EST is UTC - 5 hours. America/New_York is EST in the winter and E*D*T in the summer, so check if String timestamp = "1431941838000"; is winter or summer...

This code works ok:

Calendar calNewYork = Calendar.getInstance();
calNewYork.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println("Time in New York: " + calNewYork.get(Calendar.HOUR_OF_DAY) + ":"
    + calNewYork.get(Calendar.MINUTE));

Use this to check your time:

long timestamp = "1431941838000";
Calendar calNewYork = Calendar.getInstance();
calNewYork.setTimeZone(TimeZone.getTimeZone("America/New_York"));
calNewYork.setTime(new Date(timestamp));
System.out.println("Time in New York: " + calNewYork.get(Calendar.HOUR_OF_DAY) + ":"
    + calNewYork.get(Calendar.MINUTE));

Upvotes: 0

Related Questions