gpt4 book ai didi

ios - NSDateFormatter 格式化日期的星期几

转载 作者:行者123 更新时间:2023-11-28 22:39:32 25 4
gpt4 key购买 nike

我一直在寻找一种格式化以下 NSDate 对象的方法:

19 Feb 2013

像那样

18-25 Feb 2013

19 发生在 2 月 18 日到 25 日之间的一周内。

我没有一个简单的方法来做到这一点,NSDateFormater 是否有内置功能?我应该自己实现吗?

最佳答案

我认为 NSDateFormatter 中没有内置功能可以做到这一点。但是,Apple 有一个 example如何获取给定日期的一周的第一天和最后一天的 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];

关于ios - NSDateFormatter 格式化日期的星期几,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14962710/

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