【问题标题】:How to get local time zone date in swift 3如何在swift 3中获取本地时区日期
【发布时间】:2017-11-22 21:01:43
【问题描述】:

我以这种方式从给定日期获取年、月和日。

let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day], from: today)    

let day=components.day

但是我比现在提前一天。我该如何解决这个问题?

【问题讨论】:

  • 试试TimeZone(abbreviation: "GMT")! 换成timeZone
  • @Tj3n 但是如果我比格林威治标准时间提前 5.6 小时呢?
  • 也许是因为你提前了一天
  • @Tj3n 是的,我想获取与设备时区相关的日期
  • @user1960169 calendar.timeZone = .current 正在进行本地时间转换。您当前的时区是?

标签: ios date swift3


【解决方案1】:
let date = Date().description(with: Locale.current)
print("date ---> \(date)")

结果:日期 ---> 印度标准时间 2017 年 6 月 20 日星期二下午 4:35:15

我得到了完美的系统/本地时间。

您的代码正在运行,

let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: today)

let day = components.day
let hour = components.hour
let minute = components.minute
print("day = \(day)\nhour = \(hour)\nminute = \(minute)")

结果:
day = Optional(20)
hour = Optional(16)
minute = Optional(35)

【讨论】:

  • 这如何回答这个问题? OP 要求整数天。
  • 2018-02-14 18:30:00 +0000 前一天给我
  • @Chandni 我刚刚测试了它,它给了我 - date ---> Thursday, February 15, 2018 at 6:09:22 PM India Standard Time day = Optional(15) hour = Optional(18) minute = Optional(9) 你的设备/系统/模拟器的时区是什么?遵循您正在执行此代码的系统时区和日期
【解决方案2】:

根据documentation

如果您想要“给定时区的日期信息”,以便 显示它,你应该使用 DateFormatter 来格式化日期。

例如:

// If date is "Dec 7, 2018 at 6:34 AM" UTC
let today=Date() // is always UTC
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day], from: today)
let day = components.day  // Is 7
// To print with local version
let myFormatter = DateFormatter()
myFormatter.timeZone = TimeZone(secondsFromGMT: 3600*10)
myFormatter.dateFormat = "dd"
print(myFormatter.string(from: today))  // prints "07\n"
myFormatter.timeZone = TimeZone(secondsFromGMT: -3600*11)
print(myFormatter.string(from: today))  // prints "06\n"

【讨论】:

  • 另见Date doc:“一个特定的时间点,独立于任何日历或时区。”
【解决方案3】:

获取本地日期和时间

斯威夫特 5:

let today = Date()
let timeZone = Double(TimeZone.current.secondsFromGMT(for: today))
let localDate = Calendar.current.date(byAdding: .second, value: Int(timeZone), to: today) ?? Date()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 2014-02-22
    • 2021-01-16
    • 1970-01-01
    相关资源
    最近更新 更多