Jacob Davis
Jacob Davis

Reputation: 45

Android SimpleDateFormat not recognizing daylight time

I am trying to parse a string of time given in GMT to a new string with the user's timezone. SimpleDateFormat is parsing the time as PST while it should be PDT. Printing the current time provides the correct timezone. I have a feeling the problem might be with using a date, but I am unsure what to do.

Sample code:

try {
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a z", Locale.ENGLISH);
        Log.e("Current time", sdf.format(Calendar.getInstance().getTime()));
        sdf.applyPattern("HHmm z");
        Date date = sdf.parse("2137 GMT");
        sdf.applyPattern("hh:mm a z");
        Log.e("Parsed time", sdf.format(date));
    }catch (Exception e){ e.printStackTrace(); }

The two logs produce:

E/Current time﹕ 02:37 PM PDT
E/Parsed time﹕ 01:37 PM PST

Any help would be greatly appreciated.

Upvotes: 0

Views: 478

Answers (2)

Jacob Davis
Jacob Davis

Reputation: 45

I was finally able to figure out the issue. By default a date object is set for Jan 1, 1970. Daylight savings time does not apply during January so it wasn't using it. What I did was add the day of the year to the pattern and then get the current date from the calendar.

Updated portion:

sdf.applyPattern("D HHmm z");
Date date = sdf.parse(sdf.getCalendar().get(Calendar.DAY_OF_YEAR)+" 0420 GMT");

This correctly adjust for daylight savings time.

Upvotes: 1

Steve Kuo
Steve Kuo

Reputation: 63094

The date that's in used is during daylight savings time

Upvotes: 0

Related Questions