确定给定年份的阵亡将士纪念日NSDate [英] Determine NSDate for Memorial Day in a given year
问题描述
是否有更好的方法来确定给定年份的阵亡将士纪念日(5月的最后一个星期一)?
Is there a better way to determine the NSDate for Memorial Day (the last Monday in May) in a given year?
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日.
I see now that firstMondayInJune
in the above example doesn't work for all years; it returns May 28 for the year 2012.
谢谢,马丁R . weekdayOrdinal
完全按照我的期望去做,它以少于三行代码的形式返回了阵亡将士纪念日:
Thanks, Martin R. weekdayOrdinal
does exactly what I hoped, and it returns Memorial Day with 3 fewer lines of code:
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
:
To get the first Monday in a month, set weekdayOrdinal = 1
instead of 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
文档中:
工作日的序数单位代表工作日在广告中的位置 下一个较大的日历单位,例如月份.例如, 2 是 每月 秒 的工作日序数单位.
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.
这篇关于确定给定年份的阵亡将士纪念日NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!