-3

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?

Lukas Würzburger
  • 6,543
  • 7
  • 41
  • 75
User1985
  • 19
  • 4

2 Answers2

0

Check this:

    let addedDate = firsDateString
    let formatter = DateFormatter()
    formatter.timeZone = (NSTimeZone(name: "UTC")! as TimeZone)
    formatter.dateFormat = "yyyy-MMM-dd hh:mm a"
    let date1 = formatter.date(from: addedDate)
    print("DATE \(String(describing: date1!))")
Sanoj Kashyap
  • 5,020
  • 4
  • 49
  • 75
0

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

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
  • @User1985 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? – Joakim Danielson Mar 15 '19 at 07:48
  • @JoakimDanielson - your question is sounds good, we will discuss with questioner – Anbu.Karthik Mar 15 '19 at 07:50
  • @User1985 - one more question how will you differentiate the morning and evening in 12 hour format if you use – Anbu.Karthik Mar 15 '19 at 07:51
  • @Anbu.Karthik You should convert it into 24 hours format from 12 hours instead of excluding the AM/PM symbol. – TheTiger Mar 15 '19 at 07:54
  • @JoakimDanielson - no I am not copied, see my old answer https://stackoverflow.com/questions/42524651/convert-nsdate-to-string-in-ios-swift/42524767#42524767 – Anbu.Karthik Mar 15 '19 at 07:58