查找一周中与区域设置相关的第一天 [英] Finding the locale-dependent first day of the week
问题描述
给定 NSDate
,如何查找该日期的第一天,给定用户的区域设置。例如,我听说有些国家把星期一作为一周的第一天,其他国家使用星期天。我需要在第一种情况下返回前一个星期一,但在后一种情况下返回前一个星期日。
Given an NSDate
, how do I find the first day of that date's week, given the user's locale. For example, I've heard that some countries treat Monday as the first day of the week and others use Sunday. I need to return the preceding Monday in the first case but the preceding Sunday in the latter case.
我的尽力而为总是返回前一个星期日,不管设备应用的设置:
My best effort thus far always returns the preceding Sunday, regardless of the device settings applied:
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setLocale:[NSLocale currentLocale]];
NSDateComponents *components = [calendar components:NSYearForWeekOfYearCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit fromDate:originalDate];
[components setWeekday:1];
NSDate *firstDayOfWeek = [calendar dateFromComponents:components];
奖金问题:在iOS上,哪个设置驱动?是区域格式吗?
Bonus question: on iOS, which setting drives this? Is it the 'Region Format'?
推荐答案
尝试更改:
[components setWeekday:1];
到:
[components setWeekday:[calendar firstWeekday]];
您还应删除 NSYearForWeekOfYearCalendarUnit
code> NSWeekCalendarUnit 组件。
You should also remove the NSYearForWeekOfYearCalendarUnit
and NSWeekCalendarUnit
components.
奖金问题:区域格式应该是更改一周的第一天的设置。
Bonus Question: "Region Format" should be the setting that changes the first day of the week.
这篇关于查找一周中与区域设置相关的第一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!