Swift - 当前位置的工作日,currentCalendar() [英] Swift - Weekday by current location by currentCalendar()

查看:17
本文介绍了Swift - 当前位置的工作日,currentCalendar()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天是星期三,我有这个代码

Today is Wednesday and I have this code

let calendar:NSCalendar = NSCalendar.currentCalendar()
let dateComps:NSDateComponents = calendar.components(.CalendarUnitWeekday , fromDate: NSDate())
let dayOfWeek:Int = dateComps.weekday

dayOfWeek 是 4,但今天是保加利亚一周的第三天.今天在美国是一周的第四天吗?以及如何确定不同国家和地区的一周开始时间?在我的 iPhone 区域设置和日历设置为保加利亚日历和区域设置,它也知道我的 iMac 上的一周从星期一开始,但是当我执行代码时它写给我 4...

dayOfWeek is 4, but today is 3rd day of the week in Bulgaria. Is in USA today is 4th day of the week? And how to determine when the week starts in different countries and regions ? On my iPhone locale and calendar are set to Bulgarian calendar and locale and it knows that the week starts on Monday on my iMac also, but when I execute code it writes me 4...

推荐答案

对于公历,NSDateComponentsweekday 属性总是1 代表星期日,2 代表星期一等等.

For the Gregorian calendar, the weekday property of NSDateComponents is always 1 for Sunday, 2 for Monday etc.

NSCalendar.currentCalendar().firstWeekday

给出当前语言环境中第一个工作日的(索引),在美国可能是 1和 2 在保加利亚.因此

gives the (index of the) first weekday in the current locale, that could be 1 in USA and 2 in Bulgaria. Therefore

var dayOfWeek = dateComps.weekday + 1 - calendar.firstWeekday
if dayOfWeek <= 0 {
    dayOfWeek += 7
}

是根据您所在地区的星期几.作为单行:

is the day of the week according to your locale. As a one-liner:

let dayOfWeek = (dateComps.weekday + 7 - calendar.firstWeekday) % 7 + 1

<小时>

Swift 3 更新:

let calendar = Calendar.current
var dayOfWeek = calendar.component(.weekday, from: Date()) + 1 - calendar.firstWeekday
if dayOfWeek <= 0 {
    dayOfWeek += 7
}

这篇关于Swift - 当前位置的工作日,currentCalendar()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆