在NSDate的小时内添加3小时

时间:2013-09-10 07:05:22

标签: ios objective-c nsdate nscalendar nsdatecomponents

我想在当前日期添加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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

NSDate *CurrentTimedate = [NSDate date];    
NSLog(@"%@",CurrentTimedate);   
NSDate *newDate = [CurrentTimedate dateByAddingTimeInterval:60*60*3];
NSLog(@"%@",newDate);

答案 2 :(得分:0)

NSDate *newDate = [oldDate dateByAddingTimeInterval:hrs*60*60];