简体   繁体   中英

how to add time in current time

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.

current time  = 06:47:10 
//or should i hv to change this format to "2011-03-26 06:47:10  GMT"

 if(a= 1 and b= min ) 
  { //add 1 min to
  current time 
  } 
  else if(a= 1 and b= hour) 
  { //add 1
   hour to current time 
  } 
 else if(a= 1 and b=week )  
 { //add 1
 week to current time  
 }

Just need to add the output of the above condition to current time.

Please guide me with this.

Regards

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.

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

Swift version:

let now = NSDate().timeIntervalSince1970 // current time
let timeAfterXInterval = NSDate().dateByAddingTimeInterval(XXX).timeIntervalSince1970 // time after x sec

XXX is time in sec

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM