将带时区的日期字符串转换为 swift 中的秒数
Converting date string with timezone to seconds in swift
我有一个日期字符串:“2017 年 12 月 13 日”
时区字符串:“Asia/Kolkata”
在Swift4.0中Epoch timestamp秒的方法是什么?
这里是解决方案:
// your input
let dateStr = "13 December 2017"
let timeZoneStr = "Asia/Kolkata"
// building the formatter
let formatter = DateFormatter()
formatter.dateFormat = "d MMMM yyyy"
formatter.timeZone = TimeZone(identifier: timeZoneStr)
// extracting the epoch
let date = formatter.date(from: dateStr) // Dec 13, 2017 at 3:30 AM
let epoch = date?.timeIntervalSince1970
print(epoch ?? "") // 1513103400
有关信息,此 link:
http://userguide.icu-project.org/formatparse/datetime
是日期格式化程序的有趣来源
已更新:
使用扩展:
extension String {
func epoch(dateFormat: String = "d MMMM yyyy", timeZone: String? = nil) -> TimeInterval? {
// building the formatter
let formatter = DateFormatter()
formatter.dateFormat = dateFormat
if let timeZone = timeZone { formatter.timeZone = TimeZone(identifier: timeZone) }
// extracting the epoch
let date = formatter.date(from: self)
return date?.timeIntervalSince1970
}
}
"13 December 2017".epoch(timeZone: "Asia/Kolkata") // 1513103400
我有一个日期字符串:“2017 年 12 月 13 日”
时区字符串:“Asia/Kolkata”
在Swift4.0中Epoch timestamp秒的方法是什么?
这里是解决方案:
// your input
let dateStr = "13 December 2017"
let timeZoneStr = "Asia/Kolkata"
// building the formatter
let formatter = DateFormatter()
formatter.dateFormat = "d MMMM yyyy"
formatter.timeZone = TimeZone(identifier: timeZoneStr)
// extracting the epoch
let date = formatter.date(from: dateStr) // Dec 13, 2017 at 3:30 AM
let epoch = date?.timeIntervalSince1970
print(epoch ?? "") // 1513103400
有关信息,此 link: http://userguide.icu-project.org/formatparse/datetime 是日期格式化程序的有趣来源
已更新:
使用扩展:
extension String {
func epoch(dateFormat: String = "d MMMM yyyy", timeZone: String? = nil) -> TimeInterval? {
// building the formatter
let formatter = DateFormatter()
formatter.dateFormat = dateFormat
if let timeZone = timeZone { formatter.timeZone = TimeZone(identifier: timeZone) }
// extracting the epoch
let date = formatter.date(from: self)
return date?.timeIntervalSince1970
}
}
"13 December 2017".epoch(timeZone: "Asia/Kolkata") // 1513103400