Search code examples
javaandroiddatetimetimezoneunix-timestamp

Converted unix timestamp with a timezone addition in seconds gives a true local date time on Android emulator but not in real device?


I took a date from a web service in UNIX timestamp. I milltuplied it by 1000L then I added the timezone to it in seconds (also provided by the web service) milltiplied by 1000 to obtain the date according to the country in which the application will run and not the UTC date. In the emulator the date time provided is correct but when I tested on a real device it provided me the time with 1 hour more which does not correspond to the local time. Where is the problem?

long numberOfsecondsRise = json.getJSONObject("city").getInt("timezone");

long res=(json.getJSONObject("city").getLong("sunrise")*1000L +numberOfsecondsRise*1000) ;
 Date rise=new java.util.Date(res);
 DateFormat dfa = DateFormat.getTimeInstance();
 sunFiled.setText(getResources().getString(R.string.sunrise)+": " + dfa.format(rise));

Solution

  • Date (long date) constructor documentation says:

    Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

    This means the value is supposed to be in UTC. The time offset in seconds must be applied when formatting the date for display.

    long numberOfsecondsRise = json.getJSONObject("city").getInt("timezone");
    Date rise = new java.util.Date(json.getJSONObject("city").getLong("sunrise") * 1000L);
    
    int offsetMinutes = numberOfsecondsRise / 60;
    String sign = (offsetMinutes < 0 ? "-" : "+");
    offsetMinutes = Math.abs(offsetMinutes);
    String timeZoneID = String.format("GMT%s%d:%02d", sign, offsetMinutes / 60, offsetMinutes % 60);
    
    DateFormat dfa = DateFormat.getTimeInstance();
    dfa.setTimeZone(TimeZone.getTimeZone(timeZoneID));
    sunFiled.setText(getResources().getString(R.string.sunrise) + ": " + dfa.format(rise));