0

我想在当前日期上增加 3 小时。我正在使用以下代码添加小时,但它会在当前日期增加 6 小时。

NSDate *n = [NSDate date];
int daysToAdd = 3;  // or 60 :-)

// set up date components
NSDateComponents *components1 = [[[NSDateComponents alloc] init] autorelease];
[components1 setHour:daysToAdd];

// create a calendar   
NSCalendar *gregorian12 = [NSCalendar currentCalendar];

NSDate *newDate2 = [gregorian12 dateByAddingComponents:components toDate:n options:0];
NSLog(@"Clean: %@", newDate2);

结果是:-

2013-09-10 12:25:24.752 project[1554:c07] Clean: 2013-09-10 06:55:15 +0000
4

3 回答 3

5

试试这个

NSString *strCurrentDate;
NSString *strNewDate;
NSDate *date = [NSDate date];
NSDateFormatter *df =[[NSDateFormatter alloc]init];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterMediumStyle];
strCurrentDate = [df stringFromDate:date];
NSLog(@"Current Date and Time: %@",strCurrentDate);
int hoursToAdd = 3;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setHour:hoursToAdd];
NSDate *newDate= [calendar dateByAddingComponents:components toDate:date options:0];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterMediumStyle];
strNewDate = [df stringFromDate:newDate];
NSLog(@"New Date and Time: %@",strNewDate);

输出

Current Date and Time: Sep 10, 2013, 1:15:41 PM
    New Date and Time: Sep 10, 2013, 4:15:41 PM
于 2013-09-10T07:46:52.377 回答
2
NSDate *CurrentTimedate = [NSDate date];    
NSLog(@"%@",CurrentTimedate);   
NSDate *newDate = [CurrentTimedate dateByAddingTimeInterval:60*60*3];
NSLog(@"%@",newDate);
于 2013-09-10T07:34:14.307 回答
0
NSDate *newDate = [oldDate dateByAddingTimeInterval:hrs*60*60];
于 2013-09-10T07:14:40.217 回答