如何在当前时间添加时间

isc*_*ers 10 iphone xcode datetime ios

我对这个很困惑.

我想抓住当前时间,而不是根据条件,我想将所需时间添加到当前时间.例如.

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  
 }
Run Code Online (Sandbox Code Playgroud)

只需要将上述条件的输出添加到当前时间.

请指导我这个.

问候

Rog*_*Rog 19

你的意思是现在的时间,就像现在一样吗?

如果是这样,这将为您做到:

NSDate *now = [NSDate date]; // Grab current time
NSDate *newDate = [now addTimeInterval:XXX] // Add XXX seconds to *now
Run Code Online (Sandbox Code Playgroud)

其中XXX是以秒为单位的时间.


Mat*_*uch 14

你不应该使用 #define kOneDay 86400

在具有夏令时的时区中,每年有一天只有82800秒,而一天有90000秒.
有时甚至有一天有86401秒.(但我认为NSDateComponents也会忽略闰秒.)

如果你想做得对,你应该使用NSDateComponents.

添加一天你就像这样使用它:

NSDateComponents *offset = [[[NSDateComponents alloc] init] autorelease];
[offset setDay:1];
NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:offset toDate:date options:0];
Run Code Online (Sandbox Code Playgroud)

重要的是使用setDay:1而不是setHour:24.


要添加两周和三个小时,您将使用此功能

NSDateComponents *offset = [[[NSDateComponents alloc] init] autorelease];
[offset setWeek:2];
[offset setHour:3];
NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:offset toDate:date options:0];
Run Code Online (Sandbox Code Playgroud)

你应该明白这个想法.从最大的变化单位开始,一路向下工作.

是的,如果你关心几天,几周和几个月,这是一个多一点的工作,addTimeInterval:但是addTimeInterval:hours*60*60错了.