gpt4 book ai didi

xcode - 确定给定年份中阵亡将士纪念日的 NSDate

转载 作者:行者123 更新时间:2023-12-03 16:32:26 25 4
gpt4 key购买 nike

是否有更好的方法来确定给定年份中阵亡将士纪念日(五月的最后一个星期一)的 NSDate?

NSInteger aGivenYear = 2013 ;

NSCalendar* calendar = [NSCalendar currentCalendar] ;
NSDateComponents* firstMondayInJuneComponents = [NSDateComponents new] ;
firstMondayInJuneComponents.month = 6 ;
// Thanks, Martin R., for pointing out that `weekOfMonth` is wrong for returning the first Monday in June.
firstMondayInJuneComponents.weekOfMonth = 1 ;
firstMondayInJuneComponents.weekday = 2 ; //Monday
firstMondayInJuneComponents.year = aGivenYear ;
NSDate* firstMondayInJune = [calendar dateFromComponents:firstMondayInJuneComponents] ;

NSDateComponents* subtractAWeekComponents = [NSDateComponents new] ;
subtractAWeekComponents.week = 0 ;
NSDate* memorialDay = [calendar dateByAddingComponents:subtractAWeekComponents toDate:firstMondayInJune options:0] ;

编辑

我现在发现上面示例中的 firstMondayInJune 并不适用于所有年份;它返回 2012 年的 5 月 28 日。

谢谢,Martin RweekdayOrdinal 完全符合我的希望,它返回阵亡将士纪念日,代码少了 3 行:

NSInteger aGivenYear = 2013 ;

NSDateComponents* memorialDayComponents = [NSDateComponents new] ;
memorialDayComponents.year = aGivenYear ;
memorialDayComponents.month = 5 ;
memorialDayComponents.weekday = 2 ; //Monday
memorialDayComponents.weekdayOrdinal = -1 ; //The last instance of the specified weekday in the specified month & year.
NSDate* memorialDay = [calendar dateFromComponents:memorialDayComponents] ;

最佳答案

要获取一个月中的第一个星期一,请设置 weekdayOrdinal = 1 而不是 weekOfMonth = 1:

NSInteger aGivenYear = 2012 ;

NSCalendar* calendar = [NSCalendar currentCalendar] ;
NSDateComponents* firstMondayInJuneComponents = [NSDateComponents new] ;
firstMondayInJuneComponents.month = 6 ;
firstMondayInJuneComponents.weekdayOrdinal = 1 ;
firstMondayInJuneComponents.weekday = 2 ; //Monday
firstMondayInJuneComponents.year = aGivenYear ;
NSDate* firstMondayInJune = [calendar dateFromComponents:firstMondayInJuneComponents] ;
// --> 2012-06-04

NSDateComponents* subtractAWeekComponents = [NSDateComponents new] ;
subtractAWeekComponents.week = -1 ;
NSDate* memorialDay = [calendar dateByAddingComponents:subtractAWeekComponents toDate:firstMondayInJune options:0] ;
// --> 2012-05-28

来自 NSDateComponents 文档:

Weekday ordinal units represent the position of the weekday within the next larger calendar unit, such as the month. For example, 2 is the weekday ordinal unit for the second Friday of the month.

关于xcode - 确定给定年份中阵亡将士纪念日的 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14147450/

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