【问题标题】:Issue while converting timeStamp to local Time Zone Date将时间戳转换为本地时区日期时出现问题
【发布时间】:2016-09-06 12:08:24
【问题描述】:

我有一个从 Here 生成的时间戳

//Timestamp  1473163200000

我想根据当前时区将其转换为日期对象。

我这样做是:

NSDate *gmtDate  = [NSDate dateWithTimeIntervalSince1970:1473163200000/1000];
NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:gmtDate];




NSDate *localDate = [gmtDate dateByAddingTimeInterval:timeZoneOffset];

现在当我 po 本地日期时,我得到了这个:

  (lldb) po localDate
   2016-09-06 17:30:00 +0000

当我使用 DateFormatter 记录 localDate

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd-HH-mm-ss"];
NSString *newDate = [dateFormat stringFromDate:localDate];

我得到了这个:

(lldb) po newDate
2016-09-06-23-00-00

但我希望这是:

    Tue Sep 06 2016 17:30:00

我错过了什么? 请避免格式化我对时区更好奇。

【问题讨论】:

  • 在你的 dateFormatter 中,给他你的本地,而且 dateFormat 与你想要的格式不匹配。
  • NSString *newDate = @"Tue Sep 06 2016 17:30:00"; BTW:您对时区所做的操作在概念上是错误的。

标签: ios objective-c date nsdate nsdateformatter


【解决方案1】:

试试这个代码

NSDate *date = [NSDate dateWithTimeIntervalSince1970:1473163200000/1000];

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];

dateFormatter.dateFormat = @"EEE MMM dd yyyy HH:mm:ss";
NSString *formattedDate = [dateFormatter stringFromDate: date];

NSLog(@"formattedDate: %@",formattedDate);

输出:

formattedDate: Tue Sep 06 2016 17:30:00

【讨论】:

猜你喜欢
  • 2021-06-02
  • 2021-09-22
  • 1970-01-01
  • 2021-05-02
  • 2019-03-09
  • 2019-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多