比较没有时间组件的NSDates [英] Comparing NSDates without time component

查看:125
本文介绍了比较没有时间组件的NSDates的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个快速的游乐场,我一直在使用

In a swift playground, I have been using

NSDate.date() 

但是,这总是会附加时间元素。对于我的应用程序,我需要忽略时间元素。这在Swift中可能吗?如何做呢?即使我可以将时间元素设置为每个日期也同时工作。

But, this always appears with the time element appended. For my app I need to ignore the time element. Is this possible in Swift? How can it be done? Even if I could set the time element to be the same time on every date that would work too.

此外,我正在尝试比较两个日期,此刻我我使用以下代码:

Also, I am trying to compare two dates and at the moment I am using the following code:

var earlierDate:NSDate = firstDate.earlierDate(secondDate)

这是唯一的方法,还是可以忽略时间元素的方式?例如,如果它们是同一天但不同的时间我不想要结果。

Is this the only way or can I do this in a way that ignores the time element? For instance I don't want a result if they are the same day, but different times.

推荐答案

使用此 NSCalendar 比较iOS 8.0中日期的功能+

Use this NSCalendar function to compare dates in iOS 8.0+

func compareDate(date1: NSDate, toDate date2: NSDate, toUnitGranularity unit: NSCalendarUnit) -> NSComparisonResult

传递 .Day 作为单位

使用此函数如下:

let now = NSDate()
// "Sep 23, 2015, 10:26 AM"
let olderDate = NSDate(timeIntervalSinceNow: -10000)
// "Sep 23, 2015, 7:40 AM"

var order = NSCalendar.currentCalendar().compareDate(now, toDate: olderDate, 
                toUnitGranularity: .Hour)

switch order {
case .OrderedDescending:
    print("DESCENDING")
case .OrderedAscending:
    print("ASCENDING")
case .OrderedSame:
    print("SAME")
}

// Compare to hour: DESCENDING

order = NSCalendar.currentCalendar().compareDate(now, toDate: olderDate, 
            toUnitGranularity: .Day)

switch order {
case .OrderedDescending:
    print("DESCENDING")
case .OrderedAscending:
    print("ASCENDING")
case .OrderedSame:
    print("SAME")
}

// Compare to day: SAME

这篇关于比较没有时间组件的NSDates的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆