Search code examples
androiddatedatetimetimezonelocale

timezone clarification in java / android


I have the below code

public Long getEpochTime(String dateToGetItsEpoch) throws ParseException
{
    TimeZone timeZone = TimeZone.getTimeZone("UTC");
    final String REQUEST_DATE_FORMAT = "dd/MM/yyyy h:m";

    DateFormat format = new SimpleDateFormat(REQUEST_DATE_FORMAT);
    Date localDate = format.parse(dateToGetItsEpoch);

    Calendar cal = Calendar.getInstance(timeZone);
    cal.setTime(localDate);

    format.setTimeZone(timeZone);
    final String utcTime = format.format(cal.getTime());

    Date d = cal.getTime();

    return d.getTime();
}

If I change the locale of my device to whatever, I always get the UTC time as the return value. Which is correct, however I want to know how is this happening ? How does the device know Which timezone is the date I am giving to it so that it calculates accordingly ?


Solution

  • A Date doesn't have a time zone at all. A SimpleDateFormat does as a default for parsing and formatting; a Calendar does too; a Date doesn't.

    Given this sequence of operations:

    TimeZone timeZone = TimeZone.getTimeZone("UTC");
    DateFormat format = new SimpleDateFormat(REQUEST_DATE_FORMAT);
    Date localDate = format.parse(dateToGetItsEpoch);
    
    Calendar cal = Calendar.getInstance(timeZone);
    cal.setTime(localDate);
    
    format.setTimeZone(timeZone);
    final String utcTime = format.format(cal.getTime());
    

    ... you're initially parsing the string using the default time zone of the device, then you're formatting it in UTC. Note that the Calendar part is irrelevant here - you'd get the same result with:

    TimeZone timeZone = TimeZone.getTimeZone("UTC");
    DateFormat format = new SimpleDateFormat(REQUEST_DATE_FORMAT);
    Date date = format.parse(dateToGetItsEpoch);
    format.setTimeZone(timeZone);
    final String utcTime = format.format(date);
    

    I would personally recommend using Joda Time where possible for date/time work in Java, mind you. It's a much cleaner API than Calendar/Date.