gpt4 book ai didi

ios - 为什么这个从 NSString 得到的 NSDate 切换了月份?

转载 作者:行者123 更新时间:2023-11-28 19:08:40 25 4
gpt4 key购买 nike

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

为什么会这样?

最佳答案

你的格式字符串是错误的,月份你必须使用“MM”,所以替换:

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

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

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

关于ios - 为什么这个从 NSString 得到的 NSDate 切换了月份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17872200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com