Question

I want to add 3 hours to my current date. I am using the following code to add hours but it adds 6 hours to the current date.

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);

Result is :-

2013-09-10 12:25:24.752 project[1554:c07] Clean: 2013-09-10 06:55:15 +0000
Was it helpful?

Solution

Try this

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);

Output

Current Date and Time: Sep 10, 2013, 1:15:41 PM
    New Date and Time: Sep 10, 2013, 4:15:41 PM

OTHER TIPS

NSDate *CurrentTimedate = [NSDate date];    
NSLog(@"%@",CurrentTimedate);   
NSDate *newDate = [CurrentTimedate dateByAddingTimeInterval:60*60*3];
NSLog(@"%@",newDate);
NSDate *newDate = [oldDate dateByAddingTimeInterval:hrs*60*60];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top