gpt4 book ai didi

ios - NSDateComponents 返回错误的工作日

转载 作者:行者123 更新时间:2023-12-01 16:20:07 27 4
gpt4 key购买 nike

如果您要运行此代码:

// January 16th 2015 10:20 AM in Amsterdam
var date = NSDate(timeIntervalSince1970: 1421400000)

var formatter = NSDateFormatter()
formatter.dateFormat = "dd-MMM"

let calendar = NSCalendar.currentCalendar()
calendar.firstWeekday = 2 // default when region == Netherlands

let units = NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit
| NSCalendarUnit.WeekOfMonthCalendarUnit | NSCalendarUnit.DayCalendarUnit
| NSCalendarUnit.WeekdayCalendarUnit

// Loop days in January
for day in 1...14 {

// select day in month
var components = calendar.components(units, fromDate: date)
components.day = day

// get day and components
let _date = calendar.dateFromComponents(components)!
var _components = calendar.components(units, fromDate: _date)

// retrieve characteristics
let weekOfMonth = _components.weekOfMonth
let dayOfWeek = _components.weekday
let month = _components.month

println("\(formatter.stringFromDate(_date)) is day \(dayOfWeek) of week \(weekOfMonth) of month \(month) \n")
}

你可能会回来:

01-Jan is day 5 of week 1 of month 1
02-Jan is day 6 of week 1 of month 1
03-Jan is day 7 of week 1 of month 1
04-Jan is day 1 of week 1 of month 1
05-Jan is day 2 of week 2 of month 1
06-Jan is day 3 of week 2 of month 1
07-Jan is day 4 of week 2 of month 1
....

那些工作日是错误的。

不仅 1 月 1 日应该是第 4 天(星期四),而且奇怪的是,1 月 3 日似乎是第 1 周的第 7 天,而 1 月 4 日似乎是该周的第 1 天星期。

显然我在这里做错了什么,谁可以帮助我?

当您删除 calendar.firstWeekday = 2 行时,您将得到:

01-Jan is day 5 of week 1 of month 1
02-Jan is day 6 of week 1 of month 1
03-Jan is day 7 of week 1 of month 1
04-Jan is day 1 of week 2 of month 1
05-Jan is day 2 of week 2 of month 1
06-Jan is day 3 of week 2 of month 1
07-Jan is day 4 of week 2 of month 1
....

这更有意义,但我真的需要一周的第一天是星期一..

我已经为您设置了一个演示项目来亲自测试此行为。 https://github.com/tiemevanveen/NSDateComponentsTest/tree/master


sha指出,如果您的一周不是从 sSnday 开始,components.weekday 不会改变。奇怪的是,当你的一周从星期一开始时,components.weekOfMonth 确实发生了变化..

解决我的问题

answer对于另一个问题,如果日历的一周不以星期日开始,请让我找到一种找到所需工作日的方法。

dayOfWeek = calendar.ordinalityOfUnit(.WeekdayCalendarUnit, inUnit: .WeekCalendarUnit, forDate: _date)

该代码还可用于查找该月中的第几周或该月本身:

dayOfWeek = calendar.ordinalityOfUnit(.WeekdayCalendarUnit, inUnit: .WeekCalendarUnit, forDate: _date)
month = calendar.ordinalityOfUnit(.MonthCalendarUnit, inUnit: .YearCalendarUnit, forDate: _date)

最佳答案

一切都是正确的。如果你看Apple Documentation 。您可以看到 1 是星期日,2 - 是星期一,依此类推。所以 5 就是预期的星期四。

关于ios - NSDateComponents 返回错误的工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27990503/

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