I\'m quite confused about this one.
I want to grab, current time, than according to condition, I want to add the required time, to the current time. for example.
Swift version:
let now = NSDate().timeIntervalSince1970 // current time
let timeAfterXInterval = NSDate().dateByAddingTimeInterval(XXX).timeIntervalSince1970 // time after x sec
XXX is time in sec
You should not use #define kOneDay 86400
In timezones that have daylight saving, each year there is one day that only has 82800 seconds, and one day that has 90000 seconds.
And sometimes there is even a day that has 86401 seconds. (But I think the leap second is ignored by NSDateComponents too.)
If you want to do it right you should use NSDateComponents.
to add one day you use it like this:
NSDateComponents *offset = [[[NSDateComponents alloc] init] autorelease];
[offset setDay:1];
NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:offset toDate:date options:0];
it is important to use setDay:1
and not setHour:24
.
to add two weeks and three hours you would use this
NSDateComponents *offset = [[[NSDateComponents alloc] init] autorelease];
[offset setWeek:2];
[offset setHour:3];
NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:offset toDate:date options:0];
You should get the idea. Start with the biggest unit of change and work your way down to the smallest.
Yes, it's a little bit more work than addTimeInterval:
but addTimeInterval:hours*60*60
is wrong if you care for days, weeks and months.
'addTimeInterval:' is deprecated
You can use this now
mydate=[NSDate date];
mydate = [mydate dateByAddingTimeInterval:XXX]; //XXX in seconds
Do you mean current time, as in now?
If so, this will do it for you:
NSDate *now = [NSDate date]; // Grab current time
NSDate *newDate = [now addTimeInterval:XXX] // Add XXX seconds to *now
Where XXX is the time in seconds.