如何在 Objective-C 中的特殊日期获得一周中的星期一?

Posted

技术标签:

【中文标题】如何在 Objective-C 中的特殊日期获得一周中的星期一?【英文标题】:How can I get the monday of a week in a special date in Objective-C? 【发布时间】:2010-10-08 13:40:43 【问题描述】:

例如01.10.2010 是星期五 => 27.09.2010 是星期一。

我不知道如何管理这个。顺便说一句:我如何计算日期?

【问题讨论】:

【参考方案1】:

对于time/date calculations,使用 NSDateComponents。

清单 2 获取本周的星期日

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

在以后的版本中,有更聪明的办法:

NSCalendar *cal = [NSCalendar currentCalendar];
[cal setFirstWeekday:2];    //2 is monday. 1:Sunday .. 7:Saturday don't set it, if user's locale should determine the start of a week
NSDate *now = [NSDate date];
NSDate *monday;
[cal rangeOfUnit:NSWeekCalendarUnit  // we want to have the start of the week
       startDate:&monday             // we will write the date object to monday
        interval:NULL                // we don't care for the seconds a week has
         forDate:now];               // we want the monday of today's week

如果您确实更改了表示一周开始的工作日(星期日与星期一),则应在此 sn-p 之后将其更改回来。

【讨论】:

看起来很复杂 :> 。但这是一个很好的例子。谢谢

以上是关于如何在 Objective-C 中的特殊日期获得一周中的星期一?的主要内容,如果未能解决你的问题,请参考以下文章

Objective-C plist中的特殊字符

ORACLE如何获得日期中的年份

ORACLE如何获得日期中的年份

如何将日期时间转换为erlang中的日期名称和月份名称?

Angularjs如何获得一周内的所有日期和日期

如何在 iOS 上将“MongoDB 日期时间(ISO 日期)”解析为 NSDate(swift 和 Objective-c)