【问题标题】:Converting a unix timestamp to NSdate using local timezone使用本地时区将 unix 时间戳转换为 NSdate
【发布时间】:2012-06-10 22:47:39
【问题描述】:

我从 API 请求中以 NSDecimalNumbers 的形式返回了一些 start_timesend_times

我已经成功地将这些NSDecimalNumbers 转换为NSDates,但是代码没有考虑时区。

我需要它使用设备上的默认时区。

【问题讨论】:

标签: iphone ios objective-c nsdate


【解决方案1】:

这应该可以满足您当前语言环境的需要

double unixTimeStamp =1304245000;
NSTimeInterval _interval=unixTimeStamp;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
NSDateFormatter *formatter= [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setDateFormat:@"dd.MM.yyyy"];
NSString *dateString = [formatter stringFromDate:date];

【讨论】:

    【解决方案2】:

    Unix 时间doesn't have a time zone。它在 UTC 中定义为自 1970 年 1 月 1 日午夜以来的秒数。

    您应该使用正确的时区获取 NSDates

    [NSDate dateWithTimeIntervalSince1970:myEpochTimestamp];
    

    【讨论】:

    • 你好大卫,你的哪一个是正确的还是被接受的?
    • 在创建日期对象时,两个答案都是一样的。剩下的只是格式化。
    • 感谢您的回复,但我只关心[formatter setLocale:[NSLocale currentLocale]]; 这一行的输出可能会有所不同?
    • 是的,输出会因本地而异。同样,这只是将日期对象格式化为字符串。这是同一天。
    【解决方案3】:

    试试这样的..

    NSDate* sourceDate = ... // your NSDate
    
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
    
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    
    NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
    

    【讨论】:

      猜你喜欢
      • 2012-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 2017-08-24
      • 1970-01-01
      • 2011-03-01
      • 2019-03-09
      相关资源
      最近更新 更多