0

In swift, I have two time strings

let a = "12:03"
let b = "24:31" // = next day 00:31

If today's date is 2015-07-04, I wish to compare two dates like this

a (= 2015-07-04 12:03) vs b (= 2015-07-05 00:31)

and return the earlier datetime

Can anyone teach me the simpliest way of doing this?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Joon. P
  • 2,238
  • 7
  • 26
  • 53
  • Dates in string format are hard to compare. That's what NSDate is for. You should have code already to convert your strings to NSDate, so use that. – gnasher729 Jul 05 '15 at 05:16
  • If the format is fixed as "HH:MM" then you can simply do a string comparison. – Martin R Jul 05 '15 at 08:13

2 Answers2

0
extension NSDate {
    var day: Int {
        return NSCalendar.currentCalendar().component(.CalendarUnitDay, fromDate: self)
    }
    var month: Int {
        return NSCalendar.currentCalendar().component(.CalendarUnitMonth, fromDate: self)
    }
    var year: Int {
        return NSCalendar.currentCalendar().component(.CalendarUnitYear, fromDate: self)
    }
}



let a = "12:03"
let hourA = (a.componentsSeparatedByString(":").first ?? "").toInt() ?? 0
let minuteA = (a.componentsSeparatedByString(":").last ?? "").toInt() ?? 0

let b = "24:31"
let hourB = (b.componentsSeparatedByString(":").first ?? "").toInt() ?? 0
let minuteB = (b.componentsSeparatedByString(":").last ?? "").toInt() ?? 0

let today = NSDate()   // or your reference date

let date1 = NSCalendar.currentCalendar().dateWithEra(1, year: today.year, month: today.month, day: today.day, hour: hourA, minute: minuteA, second: 0, nanosecond: 0)!
let date2 = NSCalendar.currentCalendar().dateWithEra(1, year: today.year, month: today.month, day: today.day, hour: hourB, minute: minuteB, second: 0, nanosecond: 0)!


let myEarlierDate = date1.earlierDate(date2)   // "Jul 5, 2015, 12:03 PM"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
-1

There is compare function which gives the comparison result between two dates (First date can be either earlier or same or later than second date) In your case, first date is 'a' and second date is 'b'.

`let compareResult = a.compare(b)`

Check compareResult which can be either OrderedAscending/OrderedSame/OrderedDescending

`enum NSComparisonResult : Int {
case OrderedAscending
case OrderedSame
case OrderedDescending
}`

Then get the difference between two dates in seconds using .timeIntervalSinceDate() and then convert it into days/hours/minutes/seconds according to your requirement. You may find this link useful: Time comparisons in swift

Community
  • 1
  • 1
Ashish Verma
  • 1,776
  • 1
  • 16
  • 27