paul_f
paul_f

Reputation: 1376

Time conversion from String to Date: 12 is becoming 00 swift

I am saving a time to Firebase and then allowing the user to reload the time that was saved.

When I pull the data from the server (as a String) and then convert the time back to a Date type, it changes from 12:00 (Midday) to 00:00 (Midnight).

I can see the data on my Firebase realtime Database and it clearly says 12:00 and not midnight.

Firebase Image

Here is the code I am using to extract the data from the dictionary I've downloaded from the real-time Database.

if let gtt1hourLabTime = patientDataDictionary["1 Hour lab Time"] as? String {
      if let realgtt1HourLabTime = timeFormatTool(gtt1hourLabTime) {
                print(realgtt1HourLabTime)
                patientVC.gtt1HourLabTime = realgtt1HourLabTime
       }
}

Here is my time format Tool:

func timeFormatTool(_ dateStr: String) -> Date? {
        let simpleDateFormat = DateFormatter()
        simpleDateFormat.dateFormat = "hh:mm"

        let date = simpleDateFormat.date(from: dateStr)
        return date
}

When the time is printed it comes out like this:

2000-01-01 00:18:00 +0000

Upvotes: 1

Views: 87

Answers (1)

PoolHallJunkie
PoolHallJunkie

Reputation: 1363

Because the format you are using is hh:mm after 11:59 the format goes back to 00:00. If you want 24h format , which includes 12:xx you just need to change your date format to this:

simpleDateFormat.dateFormat = "HH:mm"

Upvotes: 3

Related Questions