Search code examples
swiftnsdate

Convert time string into date swift


I am using firebase as a backend and storing a string of time like this 7:00 PM.

I am trying to convert the string received from Firebase and convert it into NSDate so I can sort it, change the time..etc

I've looked online and come up with this code so far

dateFormatter.dateFormat = "hh:mm a"
                  dateFormatter.locale = NSLocale.current
                  dateFormatter.timeZone = NSTimeZone.local
                  let date = dateFormatter.date(from: item)
                  self.times.append(date!)
                  print("Start: \(date)")

where item is the string (7:00 PM)

When I run the app, the console returns:

Item: 9:00 AM

Start: Optional(2000-01-01 05:00:00 +0000)

Ive set timezone, locale, format. Why is the time being returned not correct?

A few other examples printed out:

Item: 1:20 PM

Start: Optional(2000-01-01 17:20:00 +0000)

Item: 9:40 AM

Start: Optional(2000-01-01 05:40:00 +0000)

Item: 10:00 AM

Start: Optional(2000-01-01 05:00:00 +0000)

Item: 12:00 PM

Start: Optional(2000-01-01 17:00:00 +0000)


Solution

  • Always remember this: Date / NSDate stores times in UTC. If your timezone is anything but UTC, the value returned by print(date) will always be different.

    You can make it print out the hour as stored in Firebase by specifying a UTC timezone. The default is the user's (i.e. your) timezone:

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "hh:mm a"
    dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
    
    let item = "7:00 PM"
    let date = dateFormatter.date(from: item)
    print("Start: \(date)") // Start: Optional(2000-01-01 19:00:00 +0000)