代码之家  ›  专栏  ›  技术社区  ›  bruno vignesh

检查两个日期是否相隔一个月

  •  1
  • bruno vignesh  · 技术社区  · 7 年前

    我想看看两个日期是否相隔一个月。我读到我应该使用这种方法 components:fromDate:toDate:options: NSCalendar

    我的代码

    #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)po now 2017-08-23 11:54:00+0000

    (lldb)po更新日期2017-08-23 11:48:00+0000

    2 回复  |  直到 7 年前
        1
  •  2
  •   Deep Moradia    7 年前

    下一行不包括年份( NSCalendarUnitYear )和白天( NSCalendarUnitDay )组件,仅月份( NSCalendarUnitMonth )包括组件。

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

    NSCalendarUnitYear公司 N日历日 获取[comps year]&[薪酬日]为0。

    这样地:

    NSDateComponents * components = [calendar components:NSCalendarUnitMonth |NSCalendarUnitYear|NSCalendarUnitDay fromDate:updateDate toDate:now options:0];
    
        2
  •  -1
  •   Abdelahad Darwish    7 年前

    你可以用这个

     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]);