Search code examples
iosswiftnsdatensdateformatter

date is not showing after convert the string to date in swift


I have strings and converting into the date format, but when I convert after the date is showing properly but time is showing the wrong format

firsDateString : 2019-Mar-15 9:00 AM
secondName : 2019-Mar-15 8:00 PM

String convert into the date format

let addedDate = firsDateString
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MMM-dd hh:mm  a"
let date1 = formatter.date(from: addedDate)
print("DATE \(date1)")

After that am getting this values:

DATE Optional(2019-03-15 03:30:00 +0000)

How can get the correct date format?


Solution

  • use like , but is not a valid answer may be it works based on your condition but follow option2 it will cover all scenario if you need

    let formatter = DateFormatter()

    formatter.dateFormat = "yyyy-MMM-dd hh:mm a"

    let date1 = formatter.date(from: "2019-Mar-15 9:00 AM")

    formatter.amSymbol = ""

    formatter.pmSymbol = ""

    let currentDateStr = formatter.string(from: date1!)

    print("currentDateStr (currentDateStr)")

    based on @JoakimDanielson point

    How can this be the accepted answer when you no longer can tell the difference between 8 in the morning and 8 in the evening

    here you need to follow the 24 hour format , I update my answer ,

    Option 2

        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MMM-dd hh:mm a"
        let date1 = formatter.date(from: "2019-Mar-15 9:00 AM")
        formatter.dateFormat = "yyyy-MMM-dd HH:mm"
        let currentDateStr = formatter.string(from: date1!)
        print("currentDateStr \(currentDateStr)")
    

    Output

    enter image description here