简体   繁体   English

NSDateFormatter格式化日期的一周

[英]NSDateFormatter format the week of the date

I've been looking for a way to format the following NSDate object: 我一直在寻找一种格式化以下NSDate对象的方法:

19 Feb 2013

Like that 像那样

18-25 Feb 2013

The 19 occurs within the week between the 18th and the 25th of Feb. 19日发生在2月18日至25日的一周内。

I couldn't an easy method to do so, is there build in functionality in to the NSDateFormater? 我不能这么简单的方法,是否在NSDateFormater中构建了功能? should I implement it myself? 我应该自己实施吗?

I don't think there is built in functionality in NSDateFormatter to do this. 我不认为NSDateFormatter中有内置功能来执行此操作。 However, Apple has an example of how to get the NSDate values for the first and last days of a the week given a date. 但是,Apple提供了一个示例 ,说明如何在给定日期的一周的第一天和最后一天获取NSDate值。 Here's their example on getting the Sunday of the current week: 这是他们获得当周星期日的例子:

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];

Since Sunday is not the beginning of the week in all locales, they also show how to get the beginning of the week as defined by the calendar's locale: 由于星期日不是所有语言环境中星期的开始,它们还会显示如何按日历的语言环境定义的星期一开始:

NSDate *today = [[NSDate alloc] init];
NSDate *beginningOfWeek = nil;
BOOL ok = [gregorian rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek
                     interval:NULL forDate: today];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM