Share Coding

Tutorials, Problems, Stuffs …

Get local time and unix time by using NSDate and NSTimeZone on IOS

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *startDate = [dateFormatter dateFromString:@"2012-02-18 00:00:00"];
NSLog(@"%@", startDate);

The result is :
2012-02-17 16:00:00 +0000

 
We can see the time is not correct since the default timezone of NSDate is GMT +000(London), we must get the systemTimeZone and add interval to the date:

NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate:startDate];
startDate = [startDate addTimeInterval:interval];
NSLog(@"%@", startDate);

The result is :
2012-02-18 00:00:00 +0000

 
For IOS4.0+, a warning will received from Xcode:

'addTimeInterval:' is deprecated.

We just change the statement:addTimeInterval:

startDate = [startDate dateByAddingTimeInterval:interval];

 
Finally, convert current time to unix timestamp:

int startTime = [startDate timeIntervalSince1970];
NSLog(@"%d",startTime);

The result is :
1329523200

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: