【发布时间】: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