Convert date to Unix time (seconds since 1970)

I want to convert a user-provided date to a number of seconds since 1970.

For example, if my application is provided with a date, 5-MAY-2011 00:00:00 +0000then I need a timestamp 1304553600(the number of seconds between this date and January 1, 1970).

+3
source share
3 answers

Assume the date is valid.

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

See the manual and NSDateFormatter for more information .

+9
source

This is the specified method for the NSDate class. see this

- (NSTimeInterval)timeIntervalSince1970

it returns you seconds (what you want).

+3
source

Use NSDateFormatter to parse a date string in a real NSDate object, and then call the -timeIntervalSince1970 method on that object to get the number you are looking for.

+1
source

All Articles