Reputation: 4986
Im sending a string to a dateFormatter with this code:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-mm-dd hh:mm a"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CST"]];
NSDate *currentDate = [NSDate date];
NSCalendar* calendario = [NSCalendar currentCalendar];
NSDateComponents* components = [calendario components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentDate];
//make new strings
NSString *adjustedOpenDateString = [NSString stringWithFormat:@"%@-%ld-%ld %@", @"2013", (long)[components month], (long)[components day], openDateString];
NSString *adjustedCloseDateString = [NSString stringWithFormat:@"%@-%ld-%ld %@", @"2013", (long)[components month], (long)[components day],closeDateString];
NSLog(@"adjustedString %@", adjustedCloseDateString); //<<<<---NSLOG1
//Convert strings to dates
NSDate *openDate = [dateFormatter dateFromString:adjustedOpenDateString];
NSDate *closeDate = [dateFormatter dateFromString:adjustedCloseDateString];
NSLog(@"BEFORE COMPONENTS open, now, close %@,%@,%@", openDate,[NSDate date], closeDate); //<<<<---NSLOG2
if ([self timeCompare:openDate until:closeDate]) {
NSLog(@"OPEN-timeCompare");
} else {
NSLog(@"CLOSED-timeCompare");
}
And I get the adjustedString NSLog logging the current date correctly:
adjustedString 2013-7-25 10:00 PM
But when I log the dates converted from strings, the month is lost...switched from july to jan
open, now, close 2013-01-25 13:00:00 +0000,2013-07-26 02:54:31 +0000,2013-01-26 04:00:00 +0000
Why does this happen?
Upvotes: 0
Views: 92
Reputation: 8538
Your format string is wrong, for month you have to use "MM", so replace:
[dateFormatter setDateFormat:@"yyyy-mm-dd hh:mm a"];
with
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm a"];
Take a look at Date Format Patterns, Unicode Technical Standard #35.
Upvotes: 3
Reputation: 6187
Switch your format string to @"yyyy-MM-dd hh:mm a"
According to the Unicode Technical Standard #35, which NSDateFormatter uses for date format strings, lowercase 'm' is for minute and uppercase is for month.
Upvotes: 1