0

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

为什么会这样?

4

2 回答 2

3

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

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

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

查看日期格式模式,Unicode 技术标准 #35。

于 2013-07-26T03:19:52.627 回答
1

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

于 2013-07-26T03:19:44.367 回答