Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateFormatter sets AM/PM by default

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?

like image 261
karl_m Avatar asked Sep 19 '25 02:09

karl_m


1 Answers

  • 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)
    
like image 131
vadian Avatar answered Sep 21 '25 18:09

vadian