【问题标题】:Convert epoch milliseconds to NSDate将纪元毫秒转换为 NSDate
【发布时间】:2015-07-07 07:46:49
【问题描述】:

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

【问题讨论】:

  • 请详细说明或放一些代码

标签: ios objective-c timestamp nsdate epoch


【解决方案1】:

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

例如:

long long milliseconds = 1576058147753;
NSTimeInterval seconds = (NSTimeInterval)milliseconds / 1000.0;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
[formatter setLocalizedDateFormatFromTemplate:@"dMMMMyyyyHHmmssSSS"];

2019 年 12 月 11 日 01:55:47.753

注意 753 的毫秒数。

【讨论】:

  • 这个函数总是会丢失毫秒,毫秒总是+0000,你的答案是错误的。
  • @Kira - 这根本不是真的。你会丢失微秒,但不会丢失毫秒。毫秒肯定不总是零。例如,NSTimeInterval of 1576058147.753,例如,产生日期为2019-12-11T09:55:47.753Z(注意毫秒)。如果您有毫秒为零的代码,那么您的问题就在其他地方。或者,如果您只是打印日期并在末尾看到 +0000,那是时区,而不是毫秒。更改为包含毫秒的格式化程序。
  • 你是对的!我错过了微秒,但不是毫秒。
【解决方案2】:

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

-(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;
}

希望这会对你有所帮助。

【讨论】:

    猜你喜欢
    • 2012-03-08
    • 2013-11-11
    • 2011-02-14
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    相关资源
    最近更新 更多