Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert time string into date swift

Tags:

swift

nsdate

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)

like image 982
huddie96 Avatar asked Feb 19 '17 21:02

huddie96


People also ask

How do I convert a string to a date in Swift?

The class we use to convert a string to a date in Swift is DateFormatter (or NSDateFormatter if you are using Objective-C).

How to convert date in Swift?

Convert Month Day Year String To Date In Swift import Foundation let dateString = "January 20, 2020" let dateFormatter = DateFormatter() dateFormatter. locale = Locale(identifier: "en_US_POSIX") dateFormatter. dateFormat = "MMMM d, yyyy" if let date = dateFormatter.

How do I change the date format in Swift 5?

dateFormat = "yyyy-MM-dd'T'HH:mm:ss. SSS'Z'" dateFormatterGetNoMs. dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" let dateFormatterPrint = DateFormatter() dateFormatterPrint. dateFormat = "MMM dd,yyyy" for dateString in isoDateArray { var date: Date?


1 Answers

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)
like image 92
Code Different Avatar answered Oct 16 '22 20:10

Code Different