How to check if the current string is in 24 hour format time or 12 hour format time in swift3?

1k Views Asked by At

I am getting a particular string from the web service which is actually a time. So I want to check whether the string which i get from web service is in 24 hour format. I have successfully appended AM and Pm with this code:

let dateAsString = "13:15"
  let dateFormatter = DateFormatter()
  dateFormatter.dateFormat = "HH:mm"

  let date = dateFormatter.date(from: dateAsString)
  dateFormatter.dateFormat = "h:mm a"
  let Date12 = dateFormatter.string(from: date!)
  print("12 hour formatted Date:",Date12)

But i wish to know whether "13:15" is greater than "12:00" as this time i am getting from webservice.

3

There are 3 best solutions below

1
vadian On

Just pass the 12-hour date format and check for nil

let dateAsString = "13:15"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm"
let is24HourFormat = dateFormatter.date(from: dateAsString) == nil
1
Ahmed Elzohry On

What you did is just formatting date to nice readable string.. But what you actually looking for is comparing between dates:

See next example for comparing two dates [Swift 3.1]

func compareDates() {

    let date1 = Date() // now
    let date2 = Date().addingTimeInterval(20) // now+20secodns

    switch date1.compare(date2) // return ComparisonResult
    {
    case .orderedAscending:
       print("date1 < date2")

    case .orderedDescending:
       print("date1 > date2")

    case .orderedSame:
       print("date1 == date2")
    }

}

And if you want to compare just times that you have already in 24h format and strings, you could just use normal comparison for strings but I don't recommend this

/// compare only times in 24h format in strings

func compareTimesInStrings() {

   let time1 = "13:00"
   let time2 = "09:05"

   if time1 < time2 {
        print("time1 < time2")

   } else if time1 > time2 {
        print("time1 > time2")

   } else {
        print("time1 == time2")

   }   

}
0
Vini App On

May be this is a long answer. But here is the another way :

let dateAsString = "13:15"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"

if let date = dateFormatter.date(from: dateAsString) {
    dateFormatter.dateFormat = "h:mm a"
    let Date12 = dateFormatter.string(from: date)
    let amRange = Date12.range(of: dateFormatter.amSymbol)
    let pmRange = Date12.range(of: dateFormatter.pmSymbol)

    if pmRange == nil {
        print("12 hours")
    } else if amRange == nil {
        print("24 hours")
    }
} else {
    print("not in the time range") // if dateAsString is > 23:59
}