0

例如,我有一个日期: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

4

2 回答 2

-1

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

NSDate *date = [oldDate dateWithTimeIntervalSinceReferenceDate:milliseconds];
于 2014-11-24T19:04:06.107 回答
-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];
于 2014-11-24T19:10:31.037 回答