【问题标题】:iOS: Date not converting correctly [duplicate]iOS:日期转换不正确[重复]
【发布时间】:2014-11-24 18:53:30
【问题描述】:

比如说,我有一个日期:2014-11-24 12:24:25 存储在一个 NSString 变量中。

我正在尝试将其转换为 NSDate 对象,以便计算未来日期:

NSDate *futureTimeStamp;

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];

NSDate *oldDate = [dateFormatter dateFromString:timestamp];

它一直告诉我旧的日期时间是:2014-11-24 06:46:06 +0000,这是不正确的。

任何想法为什么它没有正确转换它?

更新 #1:

时间戳是一个字符串。存储在该变量中的是:2014-11-24 12:58:40

当我打印出 oldDate 时,它​​会在 2014-11-24 06:58:40 +0000 中显示这一点

【问题讨论】:

  • NSDate 总是以 UTC 格式转储。
  • 无论您身在何处,您的设备都会认为它是 GMT+6。我不知道为什么,但问题是一样的。代码运行正常。
  • 看看“hh”是什么意思。
  • 当您开始在真实硬件上进行测试时,您可能应该知道local "feature"

标签: ios objective-c nsdate datetime-conversion


【解决方案1】:

尝试从 UTC 转换为本地日期

  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
  NSDate *date = [dateFormatter dateFromString:timestamp];
  NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
  NSTimeZone *previousTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
  NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date];
  NSInteger currentOffset = [previousTimeZone secondsFromGMTForDate:date];
  NSTimeInterval gmtInterval = currentGMTOffset - currentOffset;
  NSDate *localDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date];

【讨论】:

  • 这绝对帮助了我!谢谢!
  • 但是你的日期格式不对。
  • 拥有一个引用非 UTC 时区的 NSDate 是不好的做法。如果您这样做,请在 wazoo 上发表评论。
  • @HotLicks 日期格式与原始问题相匹配,添加 cmets 是您的意见!为什么答案正确时投反对票...
  • @HotLicks 那么日期格式应该是什么??
【解决方案2】:

你可以像这样进行时间转换:

NSDate *date = [oldDate dateWithTimeIntervalSinceReferenceDate:milliseconds];

【讨论】:

  • 我是 iOS 开发新手......所以我很困惑这对我有什么帮助......因为 oldDate 是问题...... oldDate 没有从字符串转换为正确的日期.
  • 您可以计算正确时间和转换日期之间的差异。然后您可以将转换后的时间转换为更正时间。检查这个developer.apple.com/library/ios/documentation/Cocoa/Conceptual/…
  • 日期正确,不需要手动移位。
  • 以上解决不了问题——只是介绍更多。
猜你喜欢
  • 2017-07-28
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 2014-11-20
  • 1970-01-01
  • 2012-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多