4

I'm trying to convert the current time and date to a timestamp format. Since the service is receiving this format for timestamps:

2018-26-11T11:38:00Z

I decided to use a format like this:

yyyy-M-dd'T'H:mm:ss'Z'

But, when I use a date formatter to convert it, I'm getting an unwanted AM/PM tag at the end by default:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-M-dd'T'H:mm:ss'Z'"
let currentTimeAndDate = Date()
let timeStamp = dateFormatter.string(from: currentTimeAndDate)
// Prints "2018-12-05T12:58:38 PMZ"

How can I remove that AM/PM by default at the end of the string?

karl_m
  • 85
  • 9
  • Possible duplicate of [Hardware-dependent NSDateFormatter dateFromString: bug (returns nil)](https://stackoverflow.com/questions/19578433/hardware-dependent-nsdateformatter-datefromstring-bug-returns-nil) – Larme Dec 05 '18 at 18:55

2 Answers2

2
  • Set the locale to fixed en_US_POSIX"

    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    
  • Or use the dedicated ISO8601 formatter

    let dateFormatter = ISO8601DateFormatter()
    let currentTimeAndDate = Date()
    let timeStamp = dateFormatter.string(from: currentTimeAndDate)
    
vadian
  • 274,689
  • 30
  • 353
  • 361
-1
  1. Use yyyy-MM-dd'T'HH:mm:ssX for the format.
  2. Set the formatter's timeZone to TimeZone(secondsFromGMT: 0).
  3. Set the locale to the special "en_US_POSIX" locale: Locale(identifier: "en_US_POSIX")

Updated code:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssX"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let currentTimeAndDate = Date()
let timeStamp = dateFormatter.string(from: currentTimeAndDate)

Or avoid all of that and use ISO8601DateFormatter.

rmaddy
  • 314,917
  • 42
  • 532
  • 579