Format Date yyyy-MM-dd HH: mm: ss at 12 o'clock


I have this format and obviously when I turn on the clock at 12 o'clock, it returns a null , if I put it at 24h, I format the date well.

How can I solve this? ! Update: For 12h I try this

let dateFormatter1 = DateFormatter()
        dateFormatter1.dateFormat = "yyyy-MM-dd hh:mm:ss"
        dateFormatter1.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
        print( "2017-01-1 14:55:08")) //if you want current date

And this returns a null

The problem resides here.

asked by Alejandro 30.03.2017 в 13:02

2 answers


EDITED Try changing the h:

let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"

what gives you the 12h or 24h format are the Hs.

HH --> 24h 

hh --> 12h  

a --> Añade AM o PM al final 


As I review in your edition, you try to create a date from a String.

Your String "2017-02-1 14:55:08" is in yyyy-MM-d HH:mm:ss If you want to spend that hour in 12h format you should do the following:

let dateFormatter = DateFormatter()
var date = Date()
dateFormatter.dateFormat = "yyyy-MM-d HH:mm:ss"
date = "2017-02-1 14:55:08")!
dateFormatter.dateFormat = "yyyy-MM-d hh:mm:ss"
let stringdate = dateFormatter.string(from: date)
let newDate12h = stringdate)
answered by 30.03.2017 в 13:09

The problem was solved by adding this:

dateFormatter.locale = Locale.init(identifier:"es_ES")
answered by 30.03.2017 в 15:55