用给定的数字约会
Making Date With Given Numbers
我有以下 Swift (Swift 3) 函数来创建日期 (Date
) 和日期组件 (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
}
如果我使用它,它将 return 格林威治标准时间。
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
}
我真正想要的 return 是一个基于这些数字的日期 (2017-01-08 22:16:50)。我怎样才能用 DateComponents
做到这一点?谢谢。
该函数 return 正确的日期。 print
函数以 UTC 格式显示日期。
顺便说一下,native 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)!
}
但如果您真的想要 UTC 日期,请取消注释设置时区的行。
NSDate
对时区一无所知。它表示独立于任何日历或时区的时间点。只有像您在这里那样打印出来时,它才会转换为 GMT。不过没关系 - 这仅用于调试。对于实际输出,使用 NSDateFormatter
将日期转换为字符串。
作为一个 hacky 解决方案,您当然可以在从组件创建日期对象时将日历配置为使用 GMT。这样你就会得到你期望的字符串。当然,任何其他与该日期相关的计算结果都可能是错误的。
我有以下 Swift (Swift 3) 函数来创建日期 (Date
) 和日期组件 (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
}
如果我使用它,它将 return 格林威治标准时间。
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
}
我真正想要的 return 是一个基于这些数字的日期 (2017-01-08 22:16:50)。我怎样才能用 DateComponents
做到这一点?谢谢。
该函数 return 正确的日期。 print
函数以 UTC 格式显示日期。
顺便说一下,native 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)!
}
但如果您真的想要 UTC 日期,请取消注释设置时区的行。
NSDate
对时区一无所知。它表示独立于任何日历或时区的时间点。只有像您在这里那样打印出来时,它才会转换为 GMT。不过没关系 - 这仅用于调试。对于实际输出,使用 NSDateFormatter
将日期转换为字符串。
作为一个 hacky 解决方案,您当然可以在从组件创建日期对象时将日历配置为使用 GMT。这样你就会得到你期望的字符串。当然,任何其他与该日期相关的计算结果都可能是错误的。