3

我正在获取日期值日期:2013-06-07 18:30:00 +0000。我试图从中减去 30 分钟,但它没有给出适当的时间。

我试过这个

 NSTimeInterval secondsPerHour = 60*30;
 NSDate *newDate = [date dateByAddingTimeInterval:-secondsPerHour];
4

6 回答 6

7

原因negativeaunsigned 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);
于 2013-04-30T04:50:57.473 回答
2

您可以使用:

NSDate *minusOneHr = [[NSDate date] dateByAddingTimeInterval:-30*60];
于 2013-04-30T04:50:29.370 回答
1

你可以试试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
于 2013-04-30T04:49:22.343 回答
1

将此代码复制粘贴到 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);
于 2013-04-30T04:58:25.747 回答
1

在斯威夫特 5

let minus30Min = Date().addingTimeInterval(-30 * 60)
于 2021-05-07T10:20:30.263 回答
0
let dateMinusThirtyMinutes = Date().subtract(30.minutes)
于 2019-05-24T00:18:19.367 回答