将日期转换为Unix时间(自1970年以来的秒数)

V.V*_*V.V 3 iphone nsdate nsdateformatter iphone-sdk-3.0 ios4

我想将用户提供的日期转换为自1970年以来的秒值.

例如,如果我的应用程序提供了日期,5-MAY-2011 00:00:00 +0000那么我想要时间戳1304553600(该日期与1970年1月1日之间的秒数).

Sol*_*ola 9

假设您的日期是有效日期.

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
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅本指南NSDateFormatter.