【问题标题】:Calendar Not return correct .weekday swift 3.1 [duplicate]日历不返回正确的.weekday swift 3.1 [重复]
【发布时间】:2017-06-08 07:39:36
【问题描述】:

我正在尝试获取给定日期对象的工作日。但它总是返回 +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

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

【问题讨论】:

  • 日历的区域设置是什么?
  • 我没有为日历对象设置任何语言环境
  • 没问题。2017-06-01 18:30:00 +0000 是 GMT/UTC 时间,即您所在时区的 2017-06-02 00:00:00,那是星期五。

标签: swift swift3


【解决方案1】:

从我的角度来看,创建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

【讨论】:

  • 在我的 iPhone 中仍然显示 6 我必须从 .weekday 中减去 1
  • 您使用的设备的时区和时区是什么?
  • 科伦坡 UTC+05:30
  • @gamal 我编辑答案现在请尝试。尝试设置日历 dateFormatter.calendar = Calendar(identifier: .gregorian)
  • @gamal 所以您的当地时间是 18:30 + 5:30 = 24:00 = 00:00 + 一天。没错,不是吗?
猜你喜欢
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-13
  • 2017-07-28
相关资源
最近更新 更多