12

I have a NSString which have the format of @"2013-01-09 06:10:10 +0000" (I am getting it from server and it is not the current time). I want to increment it by one second continuously. I can use a timer for doing it, but how to increment the time by one second?

Ramis
  • 13,985
  • 7
  • 81
  • 100
Sat
  • 1,616
  • 3
  • 22
  • 40

5 Answers5

36

Try this,

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

You can get yourDate from string using NSDateFormatter.

Anusha Kottiyal
  • 3,855
  • 3
  • 28
  • 45
3

Nowadays (2017) Apple recommends to use (NS)Calendar for all kinds of date math

Objective-C

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

Swift 3

let now = Date()
let currentCalendar = Calendar.current
let nowPlusOneSecond = currentCalendar.date(byAdding: .second, value: 1, to: now)!
vadian
  • 274,689
  • 30
  • 353
  • 361
2

add 1 second in your date like bellow..

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];
Paras Joshi
  • 20,427
  • 11
  • 57
  • 70
  • Downvote for copying code from [this question](http://stackoverflow.com/a/1654439/328360) but not fixing it up (not fixing variable names, and the code doesn't actually add one second, it adds 60 seconds) – Marko May 07 '14 at 23:43
  • @Marko i just post my code which i used before in my apps and i don't know at that time i get solution from which answer so i post my code not copied from any other's answer. i don't know about that but this is code which i posted with my code and logic only. – Paras Joshi May 08 '14 at 06:59
1

Say your date string is in var called serverString. You can get a date this way...

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

And increment it this way:

date = [date dateByAddingTimeInterval:1.0];
danh
  • 62,181
  • 10
  • 95
  • 136
0

SWIFT 3.x Solution

// Just an example to present second level date/time calculation
let time = NSDate()
let interval:Double = 5.0
let timeFiveSecondLater = time.addingTimeInterval(interval)
Trevor
  • 1,051
  • 12
  • 16