两个日期之间的天数并存储在变量中

Days between two dates and store in variable

如何将两个日期之间的计算天数存储在变量中,以便将 "days" 存储在 CloudKit

我的代码是(计算日期之间的天数):

let calendar = NSCalendar.currentCalendar()

    let components = calendar.components([.Day], fromDate: datepicked, toDate: enddate, options: [])

    print("DAYS LEFT :" , components)

结果是:

DAYS LEFT : <NSDateComponents: 0x7fd399ccb890>
Day: 1095

我这里有一段代码可以计算Objective-C中两次之间的小时数。我相信您可以重写它以使其成为现实。

- (void)updateTimer {
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"dd-MM-yyyy HH:mm:ss"];

    /* instead of conceptDate the date of the started and stopped time will be used when the database is edited so
     date is nog a seperate column but is included in the colums start and stop to display working times that exceed
     the 00.00 timestamp or take multiple days (for somewhat reason)*/

    NSDate *date1 = [df dateFromString:[NSString stringWithFormat:@"%@ %@", [self conceptDate], startedTime]];
    NSDate *date2 = [df dateFromString:[NSString stringWithFormat:@"%@ %@", [self conceptDate], [self getCurrentTime]]];
    NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];

    if( interval  < 0 ) {
        interval = [date1 timeIntervalSinceDate:date2];
    }

    int hours = (int)interval / 3600;             // integer division to get the hours part
    int minutes = (interval - (hours*3600)) / 60; // interval minus hours part (in seconds) divided by 60 yields minutes
    int seconds = (interval - (hours*3600) - (minutes*60)); // interval minus hours part (in seconds) divided by 60 yields minutes

    NSString *timeDiff = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
    _workingTime.text = [NSString stringWithFormat:@"%@",timeDiff];
 }

希望对您有所帮助。目前时差存储在 _workingTime 对象中,但当然可以存储在另一个字符串变量中。

-单击变量 components,然后在弹出视图中单击 NSDateComponents

文档中可以看到有属性day获取.Day组件的值

var day: Int

所以简单写

let day = components.day

如果你想在两天之间得到天数,那么你应该试试这个。

 func daysFrom(FromDate:NSDate,ToDate:NSDate) -> Int{
    return  NSCalendar.currentCalendar().components(NSCalendarUnit.Calendar.exclusiveOr(NSCalendarUnit.Day), fromDate: date, toDate: ToDate, options: NSCalendarOptions.WrapComponents).day
}

Swift 4

func days(from:Date,to:Date) -> Int {
    return  Calendar.current.dateComponents([.day], from: from, to: to).day!
}