0

This question is not a copy of another: I have an issue that I don't find somewhere else.

I want to convert a date as String to the Date format. This String date is supposed to be the same format as Date because I used to upload it as String in a database. Here is what the String date looks like:

"2017-03-10 22:16:00 +0000";

I'm trying to convert it like that:

    let df: DateFormatter = DateFormatter()

    df.dateFormat = "yyyy-MM-dd hh:mm:ss Z"

    print(beginDateString) // "2017-03-10 22:16:00 +0000"

    let beginDate = df.date(from: beginDateString)

    print(beginDate) // App crashs here because of nil value.

The issue is that it gives me a nil value for the variable beginDate. I also tried with other dateFormat like this one: "yyyy-MM-dd hh:mm:ss" but it still doesn't work.

Hamish
  • 78,605
  • 19
  • 187
  • 280
Paul Bénéteau
  • 775
  • 2
  • 12
  • 36

2 Answers2

3

Use yyyy-MM-dd HH:mm:ss Z not yyyy-MM-dd hh:mm:ss Z.

Because hh for hour in am/pm (1~12).

You also can do with: yyyy-MM-dd HH:mm:ss xxxx or yyyy-MM-dd HH:mm:ss XXXX, etc.

Read more

javimuu
  • 1,829
  • 1
  • 18
  • 29
1

Try this...

let beginDateString: String = "2017-03-10 22:16:00 +0000"
let df: DateFormatter = DateFormatter()

df.dateFormat = "yyyy-MM-dd HH:mm:ss Z"

if let beginDate = df.date(from: beginDateString)
{
    print(beginDate) 
}

And as @javimuu said you have to change your template.

Adolfo
  • 1,862
  • 13
  • 19