Search code examples
timezonensdatensdateformatternscalendar

Converting Date+Time Formats


I need to convert the following format into a new format using NSDateFormatter.

'Fri, 25 Mar 2011 10:16:00 -0700'.

I tried using "aaa, dd bbb YYYY HH:MM:SS ZHHMM" as format, but it doesn't work; it gives me a date way in the past.

I also need to convert it into the Eastern Time Zone when creating a new date.

The code I used is the following one:

NSDateFormatter *newDateFormatter = [[NSDateFormatter alloc] init]; 
[newDateFormatter setDateFormat:@"dd MMM YYYY HH:mm:SS"];

Solution

  • Let's break this string down into the various portions:

    Fri, 25 Mar 2011 10:16:00 -0700 becomes:

    • Fri: abbreviated day of the week
    • 25: potentially zero-padded day of the month
    • Mar: abbreviated month
    • 2011: year
    • 10: potentially zero-padded hour (in 24-hour format because there is no AM/PM)
    • 16: potentially zero-padded minute
    • 00: zero-padded second
    • -0700: time zone offset

    Now let's look at the date format patterns that NSDateFormatter supports:

    • abbreviated day of the week: EEE
    • zero-padded day of the month: dd
    • abbreviated month: MMM
    • year: y
    • zero-padded hour (24-hour): HH
    • zero-padded minute: mm
    • zero-padded second: ss
    • time zone offset: ZZZ

    Thus, your format string should be: @"EEE, dd MMM y HH:mm:ss ZZZ".