问题描述
我有以下 Swift (Swift 3) 函数来使用日期组件 (DateComponents
) 创建日期 (Date
).
I have the following Swift (Swift 3) function to make a date (Date
) with date components (DateComponents
).
func makeDate(year: Int, month: Int, day: Int, hr: Int, min: Int, sec: Int) -> NSDate {
let calendar = NSCalendar(calendarIdentifier: .gregorian)!
let components = NSDateComponents()
components.year = year
components.month = month
components.day = day
components.hour = hr
components.minute = min
components.second = sec
let date = calendar.date(from: components as DateComponents)
return date! as NSDate
}
如果我使用它,它会返回一个 GMT 日期.
If I use it, it will return a GMT date.
override func viewDidLoad() {
super.viewDidLoad()
let d = makeDate(year: 2017, month: 1, day: 8, hr: 22, min: 16, sec: 50)
print(d) // 2017-01-08 13:16:50 +0000
}
我真正想要返回的是基于这些数字的日期 (2017-01-08 22:16:50).我怎样才能用 DateComponents
做到这一点?谢谢.
What I actually want to return is a date (2017-01-08 22:16:50) literally based on those numbers. How can I do that with DateComponents
? Thanks.
推荐答案
该函数确实返回了正确的日期.它是 print
函数,它以 UTC 格式显示日期.
The function does return the proper date. It's the print
function which displays the date in UTC.
顺便说一下,您的函数的本机 Swift 3 版本是
By the way, the native Swift 3 version of your function is
func makeDate(year: Int, month: Int, day: Int, hr: Int, min: Int, sec: Int) -> Date {
var calendar = Calendar(identifier: .gregorian)
// calendar.timeZone = TimeZone(secondsFromGMT: 0)!
let components = DateComponents(year: year, month: month, day: day, hour: hr, minute: min, second: sec)
return calendar.date(from: components)!
}
但如果您真的想要 UTC 日期,请取消注释该行以设置时区.
But if you really want to have UTC date, uncomment the line to set the time zone.
这篇关于用给定的数字约会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!