我希望在目标c中添加30分钟4小时当前时间差异。
Ex:11.30 - 16.00
11.00 - 15.30 11.45至15.30
我该怎么做?
答案 0 :(得分:1)
可以使用NSCalendar
的{{3}}添加4小时30分钟,并且可以使用-dateByAddingComponents:toDate:options:
进行舍入:
NSDate *now = [NSDate date];
// This assumes you want to use the Gregorian calendar.
NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
// Add 4 hours and 30 minutes
NSDateComponents *fourAndAHalfHours = [NSDateComponents new];
fourAndAHalfHours.hour = 4;
fourAndAHalfHours.minute = 30;
NSDate *future = [calendar dateByAddingComponents:fourAndAHalfHours toDate:now options:NSCalendarMatchNextTimePreservingSmallerUnits];
// Now we want to round to next 30 minutes. If we're past the 30 minute mark, round to 0.
// Otherwise, round to 30.
NSInteger minutes = [calendar component:NSCalendarUnitMinute fromDate:future];
NSInteger roundTo = minutes >= 30 ? 0 : 30;
NSDate *rounded = [calendar nextDateAfterDate:future matchingUnit:NSCalendarUnitMinute value:roundTo options:NSCalendarMatchStrictly];
请注意,NSCalendarMatchStrictly
此处将在夏令时更改后,为您提供更改后的下一个可用小时。如果您正在寻找不同的行为,请查看-nextDateAfterDate:matchingUnit:value:options:
和NSCalendarMatchNextTimePreservingSmallerUnits
。
答案 1 :(得分:0)
试试这个:
NSDate *dt = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comps = [cal components:NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:dt];
comps.hour = 4;
if(comps.minute >= 30)
comps.minute = -(comps.minute-30);
else
comps.minute = -comps.minute;
comps.second = -comps.second;
NSDate *newDate = [cal dateByAddingComponents:comps toDate:dt options:0];