IOS Swift Date String convert to date with specific timezone & locale issue

“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).”

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 = 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



%d 位部落客按了讚: