tags:

views:

425

answers:

3

I'm trying to convert a long timestamp that is UTC to Eastern Standard Time and am totally lost. Any hints would be great!

Thanks, R

+2  A: 

Try this:

Date estTime = new Date(utcTime.getTime() + TimeZone.getTimeZone("EST").getRawOffset());

Where utcTime is Date object of UTC time (if you already have the long value - just use it)

duduamar
I thought use of the Date class was discouraged.
Ben S
Wow, awesome! Thank you very much!
rd42
Calendar creation can be quite expensive, that's i don't like using it. If performance is not an issue using it is also an option.
duduamar
How would I format it like: 11/4/03 8:14 PM
rd42
Like this:DateFormat format = new SimpleDateFormat("dd/MM/yy h:mm a");String formatted = format.format(utcTime);System.out.println(formatted);
duduamar
Thank you again duduamar!
rd42
+1  A: 
final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("EST"));
c.setTimeInMillis(longTime);

Where longTime is the number of milliseconds since the epoch in UTC time. You can then use the methods of the Calendar class to get the various components of the date/time.

Ben S
Excellent thanks!
rd42
A: 

rd42, Can you give me a little more context on this?

You say you have a "UTC timestamp". Is this stored in a database? Is it a string?

I might be able to provide you more of an answer if you can give the context you're trying to work this in.


Ok for clarity's sake what you're saying is that you have a long value that represents a timestamp in UTC.

So in that case what you're going to want to do is the following.

import java.util.Calendar;
import java.util.TimeZone;

TimeZone utcTZ= TimeZone.getTimeZone("UTC");
Calendar utcCal= Calendar.getInstance(utcTZ);
utcCal.setTimeInMillis(utcAsLongValue);

Now you're calendar object is in UTC.

To display this though you're going to want to do something like the following:

import java.text.SimpleDateFormat;
import java.util.Date;

SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz");
sdf.setTimeZone(utcTZ);
Date utcDate= utcCal.getTime();
sdf.formatDate(utcDate);

This will allow you to read in a timestamp for the UTC time zone stored as a long value and convert it to a Java Calendar or Date object.

Hope that gets you where you need to be.

Dave G
The variable is of type long with a UTC timestamp. Trying to change it from 1271101959000 to something more friendly.
rd42