I have written the following code to get the date in GMT from a unix timestamp

private Date converToDate(String unixTimeStamp)
{
    //unix timestamps have GMT time zone.
    DateFormat gmtFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
    gmtFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

    //date obtained here is in IST on my system which needs to be converted into GMT.
    Date time = new Date(Long.valueOf(unixTimeStamp) * 1000);

    String result = gmtFormat.format(time);

    return lineToDate(result, true);
}

this code upon execution has

Mon May 27 02:57:32 IST 2013 

value in the date variable and

Sun May 26 21:27:32 GMT 2013

in the result variable , How do I directly get the value in result variable into date variable ?

有帮助吗?

解决方案

This is the problem, conceptually:

//date obtained here is in IST on my system which needs to be converted into GMT.
Date time = new Date(Long.valueOf(unixTimeStamp) * 1000);

A Date doesn't have a time zone. This is the value you want. The fact that when you call toString() it converts it to your local time zone is irrelevant to the value that it's actually representing. A Date is just a number of milliseconds since the Unix epoch (1st January 1970, midnight UTC). So your whole method can be:

private static Date convertToDate(String unixTimeStamp)
{
    return new Date(Long.valueOf(unixTimeStamp) * 1000);
}

You don't need any kind of formatter, as you're not really trying to get a textual representation.

I would advise you to use Joda Time for date/time work if you can, by the way - it's a much cleaner API.

其他提示

A Date is just the wrapper for a long, which contains a number of milliseconds.

What you're seeing is the default toString() representation of the Date object, which uses your default timezone (IST) to transform the date into a readable string. If you want the date represented as a string using the GMT timezone, just do what you did: use a date format with the GMT time zone.

The Date object represents an instant on the universal timeline, and doesn't have any timezone.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top