将纪元毫秒转换为NSDate

时间:2015-04-28 12:38:45

标签: ios objective-c timestamp nsdate epoch

我想将自1970年1月1日以来经过的毫秒转换为NSDate而不会丢失毫秒。每个解决方案都说将毫秒除以1000并使用dateWithTimeIntervalSince1970。但我也希望将保存时间保持在毫秒级。

2 个答案:

答案 0 :(得分:2)

dateWithTimeIntervalSince1970的参数是NSTimeInterval,它不是整数值(它是double)。没有理由失去毫秒。在执行部门时,不要使用整数。

答案 1 :(得分:0)

您可以通过这种方式获取日期。您必须根据您的要求传递时间间隔和日期格式。

-(NSString *)getStringFromDate:(double)interval withFormat:(NSString*)format
{
    if (interval == 0)
    {
        return @"";
    }
    double seconds = interval;
    NSTimeInterval timeInterval = (NSTimeInterval)seconds;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];

    NSDateFormatter* df_utc = [[NSDateFormatter alloc] init];
    [df_utc setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    [df_utc setDateFormat:format];
    NSString *Date=[df_utc stringFromDate:date];
    return Date;
}

希望这会对你有所帮助。