【问题标题】:How to check what day of the week it is (i.e. Tues, Fri?) and compare two NSDates?如何检查一周中的哪一天(即周二、周五?)并比较两个 NSDate?
【发布时间】:2009-02-24 21:28:58
【问题描述】:

我正在寻找两个做两件事:

  1. 检查一周是否过去(基于星期几)
  2. 检查一天是否过去(基于日期)

我不确定解决此问题的最佳方法是什么,因为在比较两个 NSDate(一个在 2009 年 1 月 1 日 21:30 和另一个在 2009 年 1 月 2 日 00:30)时,我可以'不只是看看 24 小时是否已经过去,因为在这种情况下它没有。我可以通过从 NSDate 获取日期 1/1/09 来解决这个问题,但我不确定如何根据我看到的文档和谷歌链接来解决这个问题。

对于另一个问题,我不知道如何知道给定日期是一周中的哪一天。我想如果 09 年 1 月 1 日是星期二、星期一等......有没有图书馆可以让你计算这个?这显然需要考虑闰年和大量其他东西......也许有一个objective-c库来解决这个问题?

感谢您的帮助!

【问题讨论】:

    标签: iphone objective-c


    【解决方案1】:

    您可以使用NSCalendar 类的components:fromData: 消息来获取各个日期组件:

    // Sunday = 1, Saturday = 7
    int weekday = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:theDate] weekday];
    

    要比较两个日期,只需使用compare: 消息:

    switch([date1 compare:date2])
    {
    case NSOrderedSame:       /* they are the same date */ break;
    case NSOrderedAscending:  /* date1 precedes date2 */ break;
    case NSOrderedDescending: /* date2 precedes date1 */ break;
    }
    

    【讨论】:

      【解决方案2】:

      您可以为此使用NSDateComponents:

      unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
      NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
      NSDateComponents *components = [gregorian components:units fromDate:date];
      

      然后您可以像这样访问日期的各个部分:

      [components year];
      [components month];
      [components day];
      

      或者,您可以使用NSCalendar 的dateFromComponents 方法构造一个新的NSDate 对象,并比较两个NSDate 对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-17
        • 2015-03-26
        • 2021-01-11
        • 1970-01-01
        • 2012-03-02
        • 1970-01-01
        相关资源
        最近更新 更多