extension String {
func convertDescriptionStringToDate() -> Date {
// Date.dateFormatterInstance.timeZone = TimeZone(identifier:"UTC")
UTC.formatter.dateFormat = "yyyy-MM-dd hh:mm:ss Z"
let originalDate = UTC.formatter.date(from: self)
return originalDate ?? Date()
}
func decriptionStringWithFormatter(_ formatter: String) -> String {
let date = self.convertDescriptionStringToDate()
UTC.formatter.dateFormat = formatter
print(UTC.formatter.dateFormat)
let originalDateString = UTC.formatter.string(from: date)
return originalDateString
}
func stringWithFormatter(_ formatter: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = formatter
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
// dateFormatter.timeZone = TimeZone.autoupdatingCurrent
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let originalDate = dateFormatter.date(from: self)
return originalDate ?? Date()
}
}
Date().description
Date().localDescription
let date = "2017-03-11 23:52:00 +0000".decriptionStringWithFormatter("yyyy/MM/dd")
let date2 = "2017-03-11 23:52:00".stringWithFormatter("yyyy-MM-dd HH:mm:ss").localDescription
let date3 = "2017-03-11 07:52:00 pm".stringWithFormatter("yyyy-MM-dd hh:mm:ss a").description(with: Locale(identifier: "zh_cn"))
//let date2 = "2017-03-11 08:52:00 pm".stringWithFormatter("yyyy-MM-dd hh:mm:ss a")
let date4 = "2017-03-11 03:52:00 pm".stringWithFormatter("yyyy-MM-dd hh:mm:ss a")
let date1 = "2017-03-11 23:52:00".stringWithFormatter("yyyy-MM-dd HH:mm:ss").description
let date6 = "2017-03-11 23:52:00".stringWithFormatter("yyyy-MM-dd HH:mm:ss")
print(date6)
let date5 = "2017-03-11 23:52:00 +0900".stringWithFormatter("yyyy-MM-dd HH:mm:ss Z")
print(date5)
Date()
print(Date())
let date7 = "2017-03-11 23:52:00 +0000".stringWithFormatter("yyyy-MM-dd HH:mm:ss Z")
print(date7)
-
假设一个 datestr = "2017-03-11 23:52:00 +0900" ,那这时候调用stringWithFormatter,则这个方法修改formatter的timeZone不会影响结果,他转出的结果,例如date5, 打印结果 为
"2017-03-11 14:52:00 +0000\n"
date 7 因为结尾是 +0000 ,所以打印结果是在他的基础上 - 0个区时 , 即
** "2017-03-11 23:52:00 +0000\n"**.
由此得出结论,即你转换的字符串一旦带有 +00(00可以是00到12)00 或者 -0000,你写的func stringWithFormatter 里面你无论如何修改formatter的timeZone, 最终转出的结果一定是减去 这个区时(例如 +0200 代表减去 -2小时, -2000 代表加上2小时) 得到的区时为0的国际标准时间. -
看例子date6, 它会受函数stringWithFormatter结果影响, 因为现在的timeZone =UTC, 所以打印结果是 "2017-03-11 23:52:00 +0000\n" ,即他把字符串当做UTC时间转换成UTC时间,结果不变.
如果timeZone = TimeZone.current, (我们现在是在中国), 则系统认为这个字符串是中国区时时间(东八区, +0800),他把此字符串转换成UTC的Date, 即结果是
"2017-03-11 15:52:00 +0000\n".
网友评论