gpt4 book ai didi

ios - NSCalendar 返回下一年第一周上周一的错误日期

转载 作者:行者123 更新时间:2023-11-29 00:38:04 25 4
gpt4 key购买 nike

我使用下面的代码使用随机日期计算前一个星期一。哪个工作文件,但我的代码在明年日期中断。下面是相同的代码:

NSDate *date = [NSDate dateWithTimeIntervalSince1970:1483620311.228];
NSLog(@"current date ===> : %@", date);

NSCalendar *calendar;
calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[calendar setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"]];
NSTimeZone *zone = [NSTimeZone timeZoneWithName:@"Australia/Sydney"];
[calendar setTimeZone:zone];

NSDateComponents *nowComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekday | NSCalendarUnitWeekOfYear | NSCalendarUnitWeekOfMonth | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitTimeZone fromDate:date];
if (nowComponents.weekday == 1) { //If my date fall in sunday then I am moving to previous week.
[nowComponents setWeekOfYear:[nowComponents weekOfYear]-1];
}

[nowComponents setWeekday:2]; //Monday

NSDate *previousMonday = [calendar dateFromComponents:nowComponents];
NSLog(@"previousMonday date ===> : %@", previousMonday);

在日志中我得到的是:

current date ===> : 2017-01-05 12:45:11 +0000
previousMonday date ===> : 2018-01-01 12:45:11 +0000

我已经看到其他堆栈溢出资源但没有得到预期的解决方案。

最佳答案

有一种更聪明的方法可以使用 NSCalendarnextDateAfterDate 来做到这一点。在这种情况下,它可以向后搜索单个组件的匹配 NSCalendarUnitWeekday == 2

NSDate *date = [NSDate dateWithTimeIntervalSince1970:1483620311.228]; 
NSLog(@"current date ===> : %@", date);
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *previousMonday = [calendar nextDateAfterDate:date
matchingUnit:NSCalendarUnitWeekday
value:2
options:NSCalendarMatchNextTime | NSCalendarSearchBackwards];
NSLog(@"previousMonday date ===> : %@", previousMonday);

时区和区域设置并不重要。

关于ios - NSCalendar 返回下一年第一周上周一的错误日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40155470/

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