【问题标题】:Subtracting and converting NSString and NSDateNSString 和 NSDate 的减法和转换
【发布时间】:2014-11-23 10:58:19
【问题描述】:

我有以下代码:

NSString *startDate = @"2014-09-29 05:46:34 +000";

// Format the string
NSRange range = NSMakeRange(0, 19);
startDate = [startDate substringWithRange:range];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:startDate];

NSDate *trendDate = [dateFromString dateByAddingTimeInterval:-3600*12];

NSString *dateString = [NSString stringWithFormat:@"%@", trendDate];

然后我的日期字符串结束为:

@"2014-09-29 00:46:34 +000";

为什么只减 5 小时而不是 12 小时?

【问题讨论】:

  • 您应该使用 NSDateComponents 而不是使用 dateByAddingTimeInterval:NSDate。另外,您是否处于具有 7 小时差异的时区,因为您没有计算 NSString 原始日期的时区。在添加时间之前打印了什么dateFromString
  • 我发现我比传递日期的格林威治标准时间晚了 7 小时。一旦我将当前日期设置为 GMT,它就可以正常工作了。
  • 除了您的问题之外,您可能会发现这些类别很有用:journeytoios.wordpress.com/2014/09/05/…

标签: ios ios7 nsstring nsdate nsdateformatter


【解决方案1】:

不要从 startDate 字符串中获取子字符串,而是尝试这种日期格式:

dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss ZZZ"

然后

dateFromString = [dateFormatter dateFromString:startDate];

NSDate *trendDate = [dateFromString dateByAddingTimeInterval:-3600*12];

NSString *dateString = [dateFormatter stringFromDate:trendDate];

【讨论】:

    【解决方案2】:

    这是因为您要从日期字符串中删除时区,所以您会得到错误的日期

    不要从您的日期字符串中删除 +000,只需替换您的日期格式。

    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    

    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
    

    删除的代码

    NSRange range = NSMakeRange(0, 19);
    startDate = [startDate substringWithRange:range];
    

    最终代码

    NSString *startDate = @"2014-09-29 05:46:34 +000";
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
    NSDate *dateFromString = [[NSDate alloc] init];
    dateFromString = [dateFormatter dateFromString:startDate];
    
    NSDate *trendDate = [dateFromString dateByAddingTimeInterval:-(3600*12)];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-25
      相关资源
      最近更新 更多