在将当前日期追加到它之后比较时间字符串?

时间:2015-07-05 04:37:22

标签: ios swift

在swift中,我有两个时间字符串

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

如果今天的日期是2015-07-04,我希望比较两个这样的日期

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

并返回较早的日期时间

有人能教我最简单的方法吗?

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分:-1)

有比较功能,可以给出两个日期之间的比较结果(第一个日期可以早于或晚于第二个日期) 在您的情况下,第一个日期是' a'第二个日期是' b'。

`let compareResult = a.compare(b)`

检查compareResult,它可以是OrderedAscending / OrderedSame / OrderedDescending

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

然后使用.timeIntervalSinceDate()以秒为单位获取两个日期之间的差异,然后根据您的要求将其转换为天/小时/分钟/秒。 您可能会发现此链接很有用: Time comparisons in swift