If I convert "2019-01-01T00:00:00+0000" to a date, I would like the date to be the date in the string - January 1, 2019. And if I calculate the number of seconds in the time portion, I would like the result to be zero.

The problem is, when I convert my string into a date, it is stored in the UTC timezone. My locale is set to "en_US_POSIX", and my time zone is set to current. My date formatter uses "yyyy-MM-dd'T'HH:mm:ssZ". I know that the final Z means UTC, but I can't seem to figure out the correct field symbol to get the results I want.

func convertToDate(_ dateString: String) -> Date {
   let dateFormatter = DateFormatter()
   dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
   dateFormatter.locale = Locale(identifier: "en_US_POSIX")
   dateFormatter.timeZone = .current
   let date = dateFormatter.date(from: dateString)
      else {
         print("DATE ERROR:", dateString)
         return Date()
      }
   return date
} 

1 Answers

3
rmaddy On Best Solutions

If you know for sure that the date strings you wish to parse will always end with a timezone in the form +XXXX then you can trim off that timezone from the string and then parse the remaining string as local time.

func convertToDate(_ dateString: String) -> Date? {
    let minusTZ = String(dateString.dropLast(5)) // Assume the string ends with a +9999 timezone
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    let date = dateFormatter.date(from: minusTZ)
    return date
}

This will give you a local date with the same date and time in the original string regardless of the timezone of the original string.