12

我有一个 NSString,其格式为 @"2013-01-09 06:10:10 +0000" (我从服务器获取它,它不是当前时间)。我想连续增加一秒。我可以使用计时器来执行此操作,但是如何将时间增加一秒?

4

5 回答 5

36

试试这个,

NSDate *correctDate = [NSDate dateWithTimeInterval:1.0 sinceDate:yourDate];

您可以使用NSDateFormatter.

于 2013-01-09T06:14:36.643 回答
3

如今(2017 年)Apple 建议(NS)Calendar用于各种日期数学

Objective-C

NSDate *now = [NSDate date];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDate *nowPlusOneSecond = [currentCalendar dateByAddingUnit:NSCalendarUnitSecond 
                                                       value:1 
                                                      toDate:now 
                                                     options:NSCalendarMatchNextTime];

斯威夫特 3

let now = Date()
let currentCalendar = Calendar.current
let nowPlusOneSecond = currentCalendar.date(byAdding: .second, value: 1, to: now)!
于 2017-04-14T16:18:27.107 回答
2

在您的日期中添加 1 秒,如下所示..

NSDate *mydate = [NSDate date];
NSTimeInterval secondsInEightHours = 60; // you can add hours and minuts with multiply the numbers with this second..
NSDate *dateEightHoursAhead = [mydate dateByAddingTimeInterval:secondsInEightHours];
于 2013-01-09T06:25:13.590 回答
1

假设您的日期字符串在名为 serverString 的 var 中。你可以通过这种方式约会...

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss z"];
NSDate *date = [df dateFromString:serverString];

并以这种方式增加它:

date = [date dateByAddingTimeInterval:1.0];
于 2013-01-09T06:37:41.827 回答
0

SWIFT 3.x 解决方案

// Just an example to present second level date/time calculation
let time = NSDate()
let interval:Double = 5.0
let timeFiveSecondLater = time.addingTimeInterval(interval)
于 2017-04-14T15:59:37.930 回答