我正在获取日期值日期:2013-06-07 18:30:00 +0000。我试图从中减去 30 分钟,但它没有给出适当的时间。
我试过这个
NSTimeInterval secondsPerHour = 60*30;
NSDate *newDate = [date dateByAddingTimeInterval:-secondsPerHour];
原因:negative
aunsigned int
是 a positive number
。这应该有效:
NSDate *newDate = [date dateByAddingTimeInterval:-(NSTimeInterval)((u_int32_t)30*60)];
编辑:替代使用NSDateComponents
。
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setMinute:-30];
NSDate *halfHourAgo = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:yourDateHere options:0];
NSLog(@"\ncurrentDate: %@ \n halfHourAgo: %@", yourDateHere, halfHourAgo);
您可以使用:
NSDate *minusOneHr = [[NSDate date] dateByAddingTimeInterval:-30*60];
你可以试试NSDateComponents,像这样:
NSDate* yourDate = [NSDate dateWithTimeIntervalSinceNow:0]; // your date, to substract 30 mins
NSDateComponents *dc = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:yourDate];
[dc setMinute:[dc minute] - 30];
NSDate* date = [[NSCalendar currentCalendar] dateFromComponents:dc]; // 30 mins before now
或者那个:
NSDate* yourDate = [NSDate dateWithTimeIntervalSinceNow:0]; // your date, to substract 30 mins
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setMinute:-30];
NSDate* date = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:yourDate options:0]; // 30 mins before now
将此代码复制粘贴到 viewDidLoad 并首先检查结果。
NSDate *today = [[NSDate alloc] init];
NSLog(@"Today %@", today);
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setMinute:-30]; // If you want to change Month,Year,Day,Hour etc. Just change the "setMinute" to setMonth,setYear,setDay,setHour
NSDate *dateComp = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
NSLog(@"Desired Day %@", dateComp);
在斯威夫特 5
let minus30Min = Date().addingTimeInterval(-30 * 60)
let dateMinusThirtyMinutes = Date().subtract(30.minutes)