Skip to content

Instantly share code, notes, and snippets.

@tgnivekucn
Created May 23, 2023 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgnivekucn/899355c156fefc6e9ff1ca6209267695 to your computer and use it in GitHub Desktop.
Save tgnivekucn/899355c156fefc6e9ff1ca6209267695 to your computer and use it in GitHub Desktop.
IOS Swift set DateFormatter and Calendar with 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 = 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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment