swift - 日历未返回正确的.weekday swift 3.1

标签 swift swift3

我正在尝试获取给定日期对象的工作日。但它总是返回+1值。 示例:如果我给出的日期为:2017-06-01 18:30:00 +0000

它返回工作日 6 -> 星期五 应该是工作日 5 -> 星期四

我的代码:

let calendar = Calendar.current
        let day: Int = calendar.component(.weekday, from: self.month!)
        print ("---------")
        print(self.month!)
        print (day)
        switch day {
        case 1:print("Sunday")
        case 2:print("Monday")
        case 3:print("Tuesday")
        case 4:print("Wednesday")
        case 5:print("Thursday")
        case 6:print("Friday")
        case 7:print("Saturday")
        default:
            break
        }

控制台上的输出:(我给出了 2 个日期,两个日期都是错误的)

---------
2016-01-01 18:30:00 +0000
7
Saturday
---------
2017-06-01 18:30:00 +0000
6
Friday

我哪里做错了... 谢谢。

最佳答案

从我的角度来看,创建 Date 的扩展使用起来更清晰:

extension Date {
    func weekday() -> Int? {
        return Calendar.current.dateComponents([.weekday], from: self).weekday
    }
}

print(Date().weekday()!)

示例:

let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .gregorian)
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZ"
let date = dateFormatter.date(from: "2017-06-01 18:30:00 +0000")

print(date?.weekday()!) //5 In Ukraine

关于swift - 日历未返回正确的.weekday swift 3.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44429514/

相关文章:

ios - 为什么在 iOS 11.4 版本中无法获取设备 token 值和 FCM token 值?

ios - 如何在 iOS 中找到目标的 Action 函数

ios - 没有收到详细 View 的数据

swift - Mapkit - 获取高度

ios - 当远程通知到达时哪个委托(delegate)首先调用,而我的应用程序处于终止模式(不在后台)

swift3 - Alamofire 4 上传带参数

swift - XCTestCase 可选实例变量

c++ - 是否有可能直接将 C++ 与 Metal API 一起使用

ios - 用于固定 UILabel 高度的字符串

ios - 谷歌分析与 Swift 3 iOS 9