Convert date to Unix time (seconds since 1970)
I want to c开发者_运维技巧onvert a user-provided date to a value of seconds since 1970.
For example, if my app is provided with the date, 5-MAY-2011 00:00:00 +0000
, then I want the timestamp 1304553600
(the number of seconds between that date and January 1, 1970).
Assume your date is a valid date.
NSDateFormatter *dateF = [[NSDateFormatter alloc] init];
[dateF setDateStyle:NSDateFormatterFullStyle]; //this format will be according to your own.
NSDate *todayDate = [dateF dateFromString: @"5-MAY-2011 00:00:00 +0000"]; //please note, this date format must match the NSDateFormatter Style, or else return null.
NSTimeInterval inter = [todayDate timeIntervalSince1970]; //return as double
For more information please refer to this guide and the NSDateFormatter.
This is given method for NSDate class. see this
- (NSTimeInterval)timeIntervalSince1970
it returns you seconds (what you want).
Use a NSDateFormatter to parse the date string into an actual NSDate object, and then call the -timeIntervalSince1970 method on that object to get the number that you're looking for.
精彩评论