views:

55

answers:

1

I am trying to get a local time from a server UTC time. I get the UTC time form the server -- and i want to make it right for each individual Android phone whether it be in California or China.

This is the code I am using now -- however it snot working.

The time I get from the server is

"2010-08-17 19:41:13.0"

And the code I use to get the difference(in seconds) is the following:

public static long getSecondsDifference(Timestamp timeStamp) {
    final Calendar calendar = Calendar.getInstance(Locale.getDefault());

    int refrenceOffset = TimeZone.getDefault().getOffset(timeStamp.getTime());

    final long referenceSeconds = (timeStamp.getTime() + refrenceOffset) / 1000;
    final long currentTimeSeconds = (calendar.getTimeInMillis()) / 1000;

    final long differenceMinutes = (currentTimeSeconds - referenceSeconds) / 60;

    return differenceMinutes;
}

The timestamp is from the java.sql.timestamp package.

Right now the time where I am is 11:50AM -- and the method returns that the given server time is -53 minutes ago( so obviously doing something wrong :) )

A: 

It had to do with daylight savings. Since its PDT(Pacific Daylight Time) where I live -- I have to compensate.

public static long getSecondsDifference(Timestamp timeStamp) {
    final Calendar calendar = Calendar.getInstance(Locale.getDefault());

    int offset = TimeZone.getDefault().getOffset(timeStamp.getTime());

    if (TimeZone.getDefault().inDaylightTime(Calendar.getInstance().getTime())) {
        offset = offset - TimeZone.getDefault().getDSTSavings();
    }
    final long referenceSeconds = (timeStamp.getTime() + offset) / 1000;

    final long currentTimeSeconds = (calendar.getTimeInMillis()) / 1000;

    final long differenceSeconds = (currentTimeSeconds - referenceSeconds);

    return differenceSeconds;
}
hwrdprkns