我正在用swift 5做一个iOS项目。在我的一个API中,日期的格式是 "yyyy-MM-dd HH:mm:ss.m"。而从这个日期,我需要获取时间。但问题是,假设我从API得到的日期是 "1900-01-01 08:30:00.000000",当我把这个日期格式转换为YYYY-MM-dd HH:mm:ss,结果是 "1900-01-01 08:00:00",转换前的时间是08:30:00.000000,但转换后是08:00:00。为什么会出现这种情况?请帮助我。
我把我的代码加在这里。
let dateTime = "1900-01-01 08:30:00.000000"
let outFormatter = DateFormatter()
outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.m"
if let date = outFormatter.date(from: dateTime) {
//here value od date is 1900-01-01 04:18:48 +0000
outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
outFormatter.locale = tempLocale
let exactDate = outFormatter.string(from: date)
//here the value of exactDate is 1900-01-01 08:00:00
}
m
是分和 S
是毫秒,所以格式必须是 "yyyy-MM-dd HH:mm:ss.S"
.
此外,对于固定的日期格式,强烈建议将区域设置为 en_US_POSIX
let dateTime = "1900-01-01 08:30:00.000000"
let outFormatter = DateFormatter()
outFormatter.locale = Locale(identifier: "en_US_POSIX")
outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.S"
if let date = outFormatter.date(from: dateTime) {
//here value od date is 1900-01-01 04:18:48 +0000
outFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let exactDate = outFormatter.string(from: date)
//here the value of exactDate is 1900-01-01 08:00:00
}
但如果你只想从日期字符串中剥离出毫秒,有一个更简单的解决方案。
let dateTime = "1900-01-01 08:30:00.000000"
let exactDate = dateTime.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
它去掉了点和后面的任何数字。