【问题标题】:How to subtract two NSDates in Swift?如何在 Swift 中减去两个 NSDate?
【发布时间】:2016-02-29 20:39:36
【问题描述】:

我已经搜索过如何做到这一点,但答案对我不起作用,所以我再次询问。 在我的应用程序中,用户添加了任务和截止日期。如果截止日期已从当前日期过去,我想将名为“pendenciaLbl”(在单元格类中)的标签更改为“迟到”,并将截止日期标签更改为“已过截止日期”,以便用户知道截止日期已过。 我用来这样做的代码是这样的:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCellWithIdentifier("AtivCell") as? AtivCell {


        cell.configureCell(materias[indexPath.row], date: dates[indexPath.row], descricao: descricoes[indexPath.row], pendencia: pendencia[indexPath.row], categoria: categorias[indexPath.row])

        let calendar = NSCalendar.currentCalendar()
        let dateFormatter = NSDateFormatter()
        let currentDate = NSDate()
        let flags = NSCalendarUnit.Day
        if let transformedDate = dateFormatter.dateFromString(dates[indexPath.row]) {
        let components = calendar.components(flags, fromDate: transformedDate, toDate: currentDate, options: [])

            if components.day >= 1 {
                dates[indexPath.row] = "Passes due date"
                cell.pendenciaLbl.text = "Late"
                cell.pendenciaLbl.textColor = UIColor.blueColor()
            }
        }
        return cell
    } else {
        return AtivCell()
    }
}

问题是这段代码不起作用,我不知道为什么。我已经通过添加已经过去的日期(如昨天)进行了测试,但标签仍然相同。我将不胜感激。

重要提示:日期[indexPath] 的格式为“MMM, dd, yyyy”,例如 2016 年 2 月 29 日。

【问题讨论】:

  • 将 NSDate 对象存储在数据层中并将它们转换为 NSString 仅用于显示可能是个好主意 - 这将简化数据处理。

标签: swift nsdate


【解决方案1】:

NSDate 实际上只是一个 Double 包含自 Cocoa“纪元日期”以来的秒数以及方法。您可以使用 NSDate 实例方法 timeIntervalSinceReferenceDate 来比较 2 个日期:

let now = NSDate()
let later = NSDate(timeIntervalSinceNow: 300)
if later.timeIntervalSinceReferenceDate > now.timeIntervalSinceReferenceDate
{
  print( "later is greater than now")
}

创建符合 Equatable 和 Comparable 协议的 NSDate 类扩展也很容易。如果这样做,您可以使用 ==、>、

编辑:

我看到您的日期以“MMM, dd, yyyy”格式存储为字符串。在这种情况下,您需要使用该格式字符串设置您的日期格式化程序,以便在您可以比较它们之前将它们转换为日期。

一个完整的例子可能如下所示:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM, dd, yyyyy"
if let someDate = dateFormatter.dateFromString("Mar, 02, 2016")
{
  let now = NSDate()

  if someDate.timeIntervalSinceReferenceDate > now.timeIntervalSinceReferenceDate
  {
    print("someDate is greater than now")
  }
  else
  {
    print("now is >= someDate")
  }
}
else
{
  print("date string \"\(dateString)\" is invalid")
}

编辑#2:

这是扩展 NSDate 的方法,以便您可以直接使用标准不等式表达式比较日期,看看哪个更大/更小:

extension NSDate: Comparable {}

//Define the global operators for the
//Comparable protocol for comparing NSDates

public func <(lhs: NSDate, rhs: NSDate) -> Bool
{
  return lhs.timeIntervalSince1970 < rhs.timeIntervalSince1970
}
//-------------------------------------------------------------

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM, dd, yyyyy"

//The "if let" optional binding will only execute the code if the let 
//statement returns a non-nil value
if let someDate = dateFormatter.dateFromString("Jan, 02, 2016")
{
  let now = NSDate()

  if someDate > now
  {
    print("later is greater than now")
  }
  else
  {
    print("now is >= someDate")
  }
}
else
{
  print("date string \"\(dateString)\" is invalid")
}

看起来 Swift 2.0 将 Equatable 协议添加到 NSDate 的定义中,因此您可以使用 == 来查看 2 个日期是否完全匹配。我不知道他们为什么不采取下一个明显的步骤并“开箱即用”添加对 Comparable 协议的支持。不这样做似乎很荒谬。

【讨论】:

  • 也可以使用 laterDate/earlierDate/compare: 日期比较方法
  • 是的。有很多方法可以剥皮。
  • @DuncanC 你只需要定义 stackoverflow.com/questions/34487625/…
  • @LeoDabus,真的吗?这是如何运作的?编译器是否能够综合来自 &lt; 的所有其他不等式以及它是 Equatable 的事实(所以 == 已经可用)?
  • @LeoDabus,我在回答中对此发表了评论。 (似乎是在 Swift 2.0 中添加的)。我仍然感到惊讶和高兴,我只需要为&lt; 提供一个定义。
【解决方案2】:
import Foundation

let dateFormatter = NSDateFormatter()

let str = "February, 29, 2016"

let date = dateFormatter.dateFromString(str) // nil !!!!!

// you HAVE TO SET .dateFormat first!!
dateFormatter.dateFormat = "MMM, dd, yyyy"
let date2 = dateFormatter.dateFromString(str)

你没有设置 dateFormatter.dateFormat,所以你的日期总是 nil

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    • 2010-11-12
    • 1970-01-01
    • 2011-05-21
    • 2018-02-06
    • 2017-03-05
    • 1970-01-01
    相关资源
    最近更新 更多