【问题标题】:Check if two dates are one month apart检查两个日期是否相隔一个月
【发布时间】:2018-02-01 00:06:03
【问题描述】:

我正在尝试检查两个日期是否相隔 1 个月。我读到我应该从NSCalendar使用这种方法components:fromDate:toDate:options:

我的代码

#define FORMAT_DATE_TIME @"dd-MM-yyyy HH:mm"

NSDate *updateDate = [Utils getDateFromString:airport.updateOn withFormat:FORMAT_DATE_TIME];
NSDate *now = [NSDate date];
NSString *nowString = [Utils getStringFromDate:now withFormat:FORMAT_DATE_TIME];
now = [Utils getDateFromString:nowString withFormat:FORMAT_DATE_TIME];

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = [calendar components:NSCalendarUnitMonth fromDate:updateDate toDate:now options:0];

NSLog(@"%ld", (long)[comps year]);
NSLog(@"%ld", (long)[comps month]);
NSLog(@"%ld", (long)[comps day]);

这些是日志:

(lldb) 年份:9223372036854775807

(lldb) 月:0

(lldb) 日:9223372036854775807

(lldb) 现在 2017-08-23 11:54:00 +0000 发布

(lldb) po updateDate 2017-08-23 11:48:00 +0000

不应该所有的值都为零吗?

【问题讨论】:

  • 我认为这是默认的“未设置”值(相当于 2^63-1)。如果您打印 NSDateComponents 可能不会打印年份和日期,因为您没有在 components:fromDate:toDate:options: 中要求它。
  • 您不需要将日期转换为字符串。
  • 不,他们不应该。它只是未初始化的变量,其中的值是不可预测的,不应该被引用。

标签: objective-c nsdate nscalendar nsdatecomponents


【解决方案1】:

以下行不包括年 (NSCalendarUnitYear) 和日 (NSCalendarUnitDay) 组件,仅包括月 (NSCalendarUnitMonth) 组件。

NSDateComponents *components = [calendar components:NSCalendarUnitMonth fromDate:updateDate toDate:now options:0];

添加 NSCalendarUnitYearNSCalendarUnitDay 将 [comps year] 和 [comps day] 设为 0。

像这样:

NSDateComponents * components = [calendar components:NSCalendarUnitMonth |NSCalendarUnitYear|NSCalendarUnitDay fromDate:updateDate toDate:now options:0];

【讨论】:

    【解决方案2】:

    你可以用这个

     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:FORMAT_DATE_TIME];
    NSDate *updateDate  = [dateFormatter dateFromString:@"24-07-1990 15:20"];
    
    NSDate *now = [NSDate date];
    
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    
    
    NSDateComponents *comps = [calendar components:unitFlags fromDate:updateDate toDate:now options:0];
    
    
    NSLog(@"%ld", (long)[comps year]);
    NSLog(@"%ld", (long)[comps month]);
    NSLog(@"%ld", (long)[comps day]);
    

    【讨论】:

    • @bruno 再次检查我第一次没有很好地阅读你的问题
    猜你喜欢
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 2014-06-28
    • 2013-04-11
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多