Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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 = 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