我使用以下代码将字符串发送到 dateFormatter:
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");
}
我得到了adjustedString NSLog 正确记录当前日期:
adjustedString 2013-7-25 10:00 PM
但是当我记录从字符串转换的日期时,月份会丢失......从七月切换到一月
open, now, close 2013-01-25 13:00:00 +0000,2013-07-26 02:54:31 +0000,2013-01-26 04:00:00 +0000
为什么会这样?