Swift NSDate比较

时间:2015-02-08 21:01:13

标签: swift nsdate nsnotification

我需要安排通知。如果使用dateFromData时间组件的当前日期日期组件的日期早于当天,我想将其更改为第二天。这是我到目前为止所拥有的。无论我如何设置,日期比较都不起作用。它要么总是改变它,要么永远不改变它。

var dateComps = calendar.components(NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.DayCalendarUnit | NSCalendarUnit.HourCalendarUnit | NSCalendarUnit.MinuteCalendarUnit, fromDate: NSDate())

dateComps.hour = calendar.component(NSCalendarUnit.HourCalendarUnit, fromDate: dateFromData)
dateComps.minute = calendar.component(NSCalendarUnit.MinuteCalendarUnit, fromDate: dateFromData)


    if fireDate.compare(NSDate()) == NSComparisonResult.OrderedDescending {
        //change day to next day

        dateComps.day += 1
        println("Change day")
    }else{
        println("Do not change day")
    }




    let notifactionOfAmountOfWork = UILocalNotification()
        notifactionOfAmountOfWork.category = "normalNotifactionCatagory"

    notifactionOfAmountOfWork.fireDate = calendar.dateFromComponents(dateComps)

1 个答案:

答案 0 :(得分:0)

您的firstDate如何定义?以下程序有效,我刚尝试过。你可以改变comps1.day和comps2.day让它达到两个条件。

import UIKit

let calendar1 = NSCalendar.currentCalendar()
let comps1 = NSDateComponents()
comps1.day = 7
let date1 = calendar1.dateByAddingComponents(comps1, toDate: NSDate(), options: NSCalendarOptions.allZeros)

let calendar2 = NSCalendar.currentCalendar()
let comps2 = NSDateComponents()
comps2.day = 0
let date2 = calendar2.dateByAddingComponents(comps2, toDate: NSDate(), options: NSCalendarOptions.allZeros)


if date1?.compare(date2!) == NSComparisonResult.OrderedDescending
{
    println("date1 is after date 2")
}else{
    println("date1 is before date 2")
}