Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/117.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 与Swift 2的日期相比,订购相同的未返回结果_Ios_Swift_Compare_Nsdate_Nsdateformatter - Fatal编程技术网

Ios 与Swift 2的日期相比,订购相同的未返回结果

Ios 与Swift 2的日期相比,订购相同的未返回结果,ios,swift,compare,nsdate,nsdateformatter,Ios,Swift,Compare,Nsdate,Nsdateformatter,当我运行此命令时,我会在使用OrderedDescending或OrderedAscinding但不使用OrderedSame时得到一个结果,即使新年的日期是相同的 let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "mm/dd/yyyy" let christmas = dateFormatter.dateFromString("12/25/2015") let newyear = da

当我运行此命令时,我会在使用OrderedDescending或OrderedAscinding但不使用OrderedSame时得到一个结果,即使新年的日期是相同的

let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "mm/dd/yyyy"

    let christmas = dateFormatter.dateFromString("12/25/2015")

    let newyear = dateFormatter.dateFromString("11/29/2015")

    let update = dateFormatter.dateFromString("02/01/2016")

    let date2 = NSDate()

    if date2.compare(newyear!) == NSComparisonResult.OrderedSame {

        let alertController = UIAlertController(title: "", message:
            "Happy New Year. ", preferredStyle: UIAlertControllerStyle.Alert)
        alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))

        self.presentViewController(alertController, animated: true, completion: nil)

    }

    if date2.compare(christmas!) == NSComparisonResult.OrderedDescending {

        let alertController = UIAlertController(title: "", message:
            "Merry Christmas.", preferredStyle: UIAlertControllerStyle.Alert)
        alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))

        self.presentViewController(alertController, animated: true, completion: nil)

    }De

你的第一期是你的日期格式。您需要“MM/dd/yyyy”。另外,
NSDate()
返回当前日期(包括时间),因此它与不包括给定时间的格式“MM/dd/yyyy”中的日期不完全相同,即使一年中的日期相同。因此,您应该使用
NSCalendar
的日期比较函数,使用单位粒度.Day,而不是NSDate的比较函数

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"

let newyear = dateFormatter.dateFromString("11/29/2015")
let date2 = NSDate() // Currently 11/29/2015

let order = NSCalendar.currentCalendar().compareDate(newyear!, toDate: date2,
    toUnitGranularity: .Day)

if order == NSComparisonResult.OrderedSame {
        print("same")
}