如何将两个日期之间的计算天数存储在变量中,以便我可以在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
答案 0 :(得分:1)
⌥ - 点击变量components
,然后点击弹出视图中的NSDateComponents
。
在文档中,您可以看到有一个属性day
来获取.Day
组件的值。
var day:Int
所以简单地写一下
let day = components.day
答案 1 :(得分:0)
我这里有一段代码,用于计算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对象中,但当然可以存储在另一个字符串变量中。
答案 2 :(得分:0)
如果你想要两天之间的日子,那么你应该尝试一下。
func daysFrom(FromDate:NSDate,ToDate:NSDate) -> Int{
return NSCalendar.currentCalendar().components(NSCalendarUnit.Calendar.exclusiveOr(NSCalendarUnit.Day), fromDate: date, toDate: ToDate, options: NSCalendarOptions.WrapComponents).day
}
答案 3 :(得分:0)
Swift 4
func days(from:Date,to:Date) -> Int {
return Calendar.current.dateComponents([.day], from: from, to: to).day!
}