8

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)

8
  • For a start, the format for 12 hour am/pm time is "hh", not "HH"
    – Martin R
    Feb 19, 2017 at 21:42
  • That was actually a mistake, I did have it as hh:mm a (Edited the post)
    – huddie96
    Feb 19, 2017 at 21:43
  • What is your timezone?
    – Martin R
    Feb 19, 2017 at 21:45
  • I guess that you live in a 5 hours difference from GMT+0? Right? That explains the hour issue. For the year/month/day, it's because your string doesn't contains any information about it, so it's putting it a the reference 2000.
    – Larme
    Feb 19, 2017 at 21:46
  • Yes I am. How do I fix it then? Is there anyway to have it show 9:00 AM no matter what ?
    – huddie96
    Feb 19, 2017 at 21:48

1 Answer 1

19

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)
3
  • 1
    Is it possible to use current date instead of 2000-01-01?
    – Shmidt
    Nov 12, 2020 at 3:33
  • That's a bad idea. "Current date" changes everyday. You don't care about the date part, so it's best to choose a fixed date Nov 12, 2020 at 3:35
  • That's exactly what I needed for my project. I already figured out - I have to set 'defaultDate' to make it work.
    – Shmidt
    Nov 12, 2020 at 3:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.