Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment one second by a NSDate object

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?

like image 811
Sat Avatar asked Jan 09 '13 06:01

Sat


2 Answers

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)!
like image 76
vadian Avatar answered Oct 19 '22 03:10

vadian


Try this,

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

You can get yourDate from string using NSDateFormatter.

like image 36
Anusha Kottiyal Avatar answered Oct 19 '22 04:10

Anusha Kottiyal