gpt4 book ai didi

iphone - 如何计算本周的第一个 NSDate?

转载 作者:行者123 更新时间:2023-12-03 18:23:40 25 4
gpt4 key购买 nike

即:

  NSDate *firstDayOfWeek = [[NSDate date] firstDayOfWeek];

例如,今天是 8 月 19 日,我想从上面的代码行获取 2010-08-15 12:00amNSDate 。谢谢!

最佳答案

我认为这个线程响应了您正在寻找的内容:http://www.cocoabuilder.com/archive/cocoa/211648-nsdatecomponents-question.html#211826

但请注意,它不会将星期一视为一周的第一天,因此您可能需要通过减去 [gregorian firstWeekday] 来稍微调整它而不仅仅是1 。另外,我将其修改为使用 -currentCalendar ,但这取决于你:-)

NSDate *today = [NSDate date];
NSCalendar *gregorian = [NSCalendar currentCalendar];

// 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];
/* Substract [gregorian firstWeekday] to handle first day of the week being something else than Sunday */
[componentsToSubtract setDay: - ([weekdayComponents weekday] - [gregorian firstWeekday])];
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];

关于iphone - 如何计算本周的第一个 NSDate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3519207/

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