I am retrieving some dates from a remote server. Unfortunately one of the possible formats is just h:mm:a
Example of data I downloaded yesterday May, 21, 2013:
1) 04:36PM EDT
2) 11:51PM EDT
The data server TimeZone is "America/New_York".
My data TimeZone is "Europe/Rome".
This is the code I've written and until this morning at 5am I thought it worked:
NSDate *myDate = @"04:36PM EDT"; //11:51PM EDT (I know the date is May, 21 2013 but it is not in the data!)
NSArray *component = [mydate componentsSeparatedByString:@" "];
//Remove any reference to the TimeZone
//set it in the dateFormatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat =@"MM dd yyyy h:mma";
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
dateFormatter.timeZone = [[NSTimeZone alloc] initWithName:@"America/New_York"];
//Create a valid date for the hour
NSDate *date = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];
NSDate *dateObject = [self.dateFormatter dateFromString: [NSString stringWithFormat:@"%u %u %u %@",
dateComponents.month,
dateComponents.day,
dateComponents.year,
[component objectAtIndex:0]]];
//Convert to local timeZone
dateFormatter.timeZone = [NSTimeZone localTimeZone]; // @"Europe/Rome"
dateFormatter.dateStyle = NSDateFormatterShortStyle;
dateFormatter.timeStyle = NSDateFormatterLongStyle;
NSString *localTimeZoneDate = dateFormatter stringFromDate:[dateObject];
NSLog(@"Local Time Zone Date = %@", localTimeZoneDate);
Output
While yesterday the code seemed to work fine because when I made the tests I still was in the 6 hour timespan that kept me in the same day, the May 21, this morning I found it doesn't. The problem is in the creation of the right date.
1) 04:36PM EDT ----> 22/05/2013 22:36:00 CEST
The correct output should have been 21/05/2013 22:36 CEST
2) 11:51PM EDT ----> 23/05/2013 05:51:00 CEST
The correct output should have been 22/05/2013 05:51 CEST
What would be the best code to handle this special case?
Thanks
Nicola