我有以下代码:
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个小时?
答案 0 :(得分: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];
答案 1 :(得分:0)
因为您要从日期字符串中删除时区错误日期
而不是从日期字符串中删除+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)];