Date()显示错误的时间

时间:2019-11-19 14:36:50

标签: ios swift xcode

我正在使用该库作为日历:https://github.com/CVCalendar/CVCalendar

然后我尝试获取用户的当前日期和时间,以便在日历中显示正确的日期。

但是当我尝试执行print("Date: \(Date())")时,我得到以下输出:

  

2019-11-19 14:32:03 +0000

但是,如果这是正确的,则应该是这样的:

  

2019-11-19 15:32:03 +0000

(我住在挪威)。所以给我一个小时的错误。

关于做什么的任何提示?

1 个答案:

答案 0 :(得分:2)

来自Apple's documentation

  

日期独立于特定的日历或时区。至   代表用户的日期,您必须在   日历。

您需要Calendar的帮助:

let calendar = Calendar(identifier: .gregorian)
let currentDate = Date()
print(calendar.dateComponents(in: calendar.timeZone, from: currentDate))

输出将是:

calendar: gregorian (fixed) timeZone: Europe/Bratislava (current) era: 1 year: 2019 
month: 11 day: 19 hour: 15 minute: 47 second: 14 nanosecond: 285109996 weekday: 3 weekdayOrdinal: 3 quarter: 0 weekOfMonth: 4 weekOfYear: 47 yearForWeekOfYear: 2019 isLeapMonth: false 

因此您可以随后访问calendar的组件,例如hourminute等。

更新:

@Camile使用DateFormatter在评论中回答了他:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss:Z"
dateFormatter.timeZone = calendar.timeZone
dateFormatter.string(from:currentDate)

会给你

2019-11-19 16:38:03:+0100
相关问题