你如何获得从过去的日期到现在的秒数?

时间:2015-01-25 06:08:28

标签: nsdate nstimeinterval

如何使用NSTimeInterval获取自1980-01-01 00:00:00 +1100以来经过的秒数?

// I need the function to use something like and am having an issue 

NSDate *aDate = (NSDate*)@"1980-01-01 00:00:00 +1100";
NSDate *seconds = [NSDate dateWithTimeInterval:60*60*24 sinceDate:aDate];
NSLog(@"seconds since Jan 1980 %@",seconds);

// I am trying to replace the following
//NSTimeInterval dateinterval = [[NSDate date] timeIntervalSince1970];

NSTimeInterval dateinterval = seconds;

NSDate仅在+0000处检索GMT,这对于实际应用程序没有帮助。当地日期是强制性的。

这太难了还是不能这样做?

1 个答案:

答案 0 :(得分:0)

您正在初始化NSDate对象错误。您无法直接将NSString转换为NSDate,您需要使用NSDateFormatter

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss z";

NSDate *aDate = [formatter dateFromString:@"1980-01-01 00:00:00 +1100"];
NSDate *now = [NSDate date];

NSTimeInterval seconds = [now timeIntervalSinceDate:aDate];

要格式化其他时区的日期,请使用新的NSDateFormatter并设置其localtimeZone