我一直在寻找一种格式化以下 NSDate 对象的方法:
19 Feb 2013
像那样
18-25 Feb 2013
19 发生在 2 月 18 日至 25 日之间的一周内。
我没有一个简单的方法可以做到这一点,NSDateFormater 中是否有内置功能?我应该自己实施吗?
我一直在寻找一种格式化以下 NSDate 对象的方法:
19 Feb 2013
像那样
18-25 Feb 2013
19 发生在 2 月 18 日至 25 日之间的一周内。
我没有一个简单的方法可以做到这一点,NSDateFormater 中是否有内置功能?我应该自己实施吗?
我认为 NSDateFormatter 中没有内置功能可以做到这一点。但是,Apple 有一个示例,说明如何获取给定日期的一周的第一天和最后一天的 NSDate 值。这是他们获取本周星期日的示例:
NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit
fromDate:today];
/*
Create a date components to represent the number of days to subtract from the current date.
The weekday value for Sunday in the Gregorian calendar is 1, so subtract 1 from the number of days to subtract from the date in question. (If today is Sunday, subtract 0 days.)
*/
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay: 0 - ([weekdayComponents weekday] - 1)];
NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract
toDate:today options:0];
/*
Optional step:
beginningOfWeek now has the same hour, minute, and second as the original date (today).
To normalize to midnight, extract the year, month, and day components and create a new date from those components.
*/
NSDateComponents *components =
[gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit |
NSDayCalendarUnit) fromDate: beginningOfWeek];
beginningOfWeek = [gregorian dateFromComponents:components];
由于星期日不是所有语言环境中的一周的开始,它们还显示了如何获取日历语言环境定义的一周的开始:
NSDate *today = [[NSDate alloc] init];
NSDate *beginningOfWeek = nil;
BOOL ok = [gregorian rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek
interval:NULL forDate: today];