比较没有时间分量的 NSDates [英] Comparing NSDates without time component

查看:21
本文介绍了比较没有时间分量的 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.

推荐答案

使用这个Calendar函数在iOS 8.0+中比较日期

Use this Calendar function to compare dates in iOS 8.0+

func compare(_ date1: Date, to date2: Date, toGranularity component: Calendar.Component) -> ComparisonResult


传递 .day 作为单位

使用该函数如下:

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

var order = Calendar.current.compare(now, to: olderDate, toGranularity: .hour)

switch order {
case .orderedDescending:
    print("DESCENDING")
case .orderedAscending:
    print("ASCENDING")
case .orderedSame:
    print("SAME")
}

// Compare to hour: DESCENDING

var order = Calendar.current.compare(now, to: olderDate, toGranularity: .day)


switch order {
case .orderedDescending:
    print("DESCENDING")
case .orderedAscending:
    print("ASCENDING")
case .orderedSame:
    print("SAME")
}

// Compare to day: SAME

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

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