首页 > 解决方案 > 获取特定时区的当前日期

问题描述

我正在尝试在用户选择的时区中获取当前日期,但是尽管使用了 stackoverflow 上其他答案中的函数,但除了当前日期之外,我什么也得不到。我用的是这个:

func dateIn(timeZone: TimeZone) -> Date {
let now = Date()
var calendar = Calendar.current
calendar.timeZone = timeZone
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: now)

let date = calendar.date(from: components) ?? Date()


   return date
}

如果有人能帮助我理解为什么我没有在时区获得日期,我将非常感激,尽管我将日历的时区更改为该时区。

标签: swifttimezonensdatenscalendar

解决方案


推荐阅读