为什么NSDate从NSString获得月份切换?

时间:2013-07-26 03:04:07

标签: ios nsdate

我使用以下代码将字符串发送到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");
}

我得到adjustString NSLog正确记录当前日期:

adjustedString 2013-7-25 10:00 PM

但是当我记录从字符串转换的日期时,月份将丢失...从7月切换到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

为什么会这样?

2 个答案:

答案 0 :(得分:3)

您的格式字符串错误,因此您必须使用“MM”,因此请替换:

[dateFormatter setDateFormat:@"yyyy-mm-dd hh:mm a"];

[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm a"];

查看Date Format Patterns,Unicode技术标准#35。

答案 1 :(得分:1)

将格式字符串切换为@"yyyy-MM-dd hh:mm a"根据Unicode Technical Standard #35,NSDateFormatter用于日期格式字符串,小写“m”表示分钟,大写表示月份。