El *_*ato 8 nsdate nscalendar nsdatecomponents swift3
我有以下Swift(Swift 3)函数来生成一个Date带日期components(DateComponents)的date().
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
}
Run Code Online (Sandbox Code Playgroud)
如果我使用它,它将返回GMT日期.
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
}
Run Code Online (Sandbox Code Playgroud)
我真正希望返回的是一个基于这些数字的日期(2017-01-08 22:16:50).我怎么能这样做DateComponents?谢谢.
vad*_*ian 13
该函数确实返回正确的日期.它print是以UTC显示日期的功能.
顺便说一下,你的函数的原生 Swift 3版本是
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)!
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您确实希望拥有UTC日期,请取消注释该行以设置时区.
| 归档时间: |
|
| 查看次数: |
7834 次 |
| 最近记录: |