“Handle the issue of getting unexpected values from the date format and calendar when the region is Thailand: (By setting the locale to en_US_POSIX)."
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func toGmtDate(year: Int, month: Int, date: Int, hour: Int, minute: Int, second: Int) -> Date? { | |
let str = String(format: "%04d-%02d-%02d %02d:%02d:%02d+0800", | |
year, month, date, | |
hour, minute, second) | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZ" | |
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // Set locale to POSIX | |
if let date = dateFormatter.date(from: str) { | |
return date | |
} else { | |
return nil | |
} | |
} | |
func convertDateToCalendar(date: Date) -> DateComponents { | |
var calendar = Calendar(identifier: .gregorian) | |
calendar.locale = Locale(identifier: "en_US_POSIX") // Set locale to POSIX | |
if let timezone = TimeZone(identifier: "Asia/Taipei") { | |
calendar.timeZone = timezone | |
} | |
let dateComponents = calendar.dateComponents([.year, .month, .day], from: date) | |
return dateComponents | |
} |
補充:
en_US_POSIX和en_US的差別:
https://www.cnblogs.com/tcan/p/4611269.html