0

我正在使用下面提供的代码来显示时间和日期。任何人都可以帮助我以秒为单位自动更改时间并以一天为单位更改日期吗?

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];

NSDate *now = [[NSDate alloc] init];

NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];

NSLog(@"\n"

      "theDate: |%@| \n"
      "theTime: |%@| \n"
      , theDate, theTime);

[dateFormat release];
[timeFormat release];
[now release];
4

3 回答 3

3

您可以使用 NSTimer,特别是scheduleTimerWithTimeInterval:target:selector:userInfo:repeats:。您可以使用 1 作为时间间隔。

于 2009-06-29T16:57:58.427 回答
1

使用NSDateComponents类。例如,要在日期上加上一天零一秒:

NSDate *startDate = [NSDate date];
unsigned unitFlags = NSDayCalendarUnit | NSSecondCalendarUnit;

NSCalendar *curr = [NSCalendar currentCalendar];
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
oneDay.day = 1;
oneDay.second = 1;

NSDate* adjustedDate = [curr dateByAddingComponents:oneDay 
                                             toDate:startDate 
                                            options:0]; 
于 2009-06-29T17:49:49.237 回答
0

日期和时间编程指南

于 2009-06-29T16:57:40.237 回答