NSDateFormatter在ios中显示错误的日期?

时间:2016-03-18 19:58:03

标签: ios objective-c nsdate nsdateformatter

我有这个日期格式为“2016-03-16”的NSString,我添加了以下代码,以正确的NSDate格式获得相同的日期但返回“2016-03-15 18:30:00 +0000”。如何在NSDate中获得相同的“2016-03-16”?

  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    dateFormatter.dateFormat = @"yyyy-MM-dd";
    NSString *datePart = [dateFormatter stringFromDate:dateFromString];//2016-03-16

    NSDate *dateValue = [dateFormatter dateFromString:datePart];
    NSLog(@"%@----",dateValue); //" 2016-03-15 18:30:00 +0000 

3 个答案:

答案 0 :(得分:5)

您当地的时区大概是UTC + 5:30。您指定的是日期而不是时间,因此时间暗示为午夜。当地时区16日午夜是UTC时间前一天(15日)的18:30,这就是为什么你会得到“2016-03-15 18:30:00 +0000”

当您使用NSLog(@"%@----",dateValue)记录日期时,您实际上正在调用[dateValue description],它使用UTC显示日期。

您可以使用NSLog(@"%@----",[dateValue descriptionWithCalendarFormat:nil timeZone:[NSTimeZone localTimeZone] locale:nil]),然后您会在当前时区看到日期。

请注意,descriptiondescriptionWithCalendarFormat方法之类的关联方法仅用于调试,您应该使用NSDateFormatter将日期转换为字符串。 iOS_Binod的答案显示了一种方法。

答案 1 :(得分:3)

您尝试在控制台中打印NSDate实例。这就是您的代码在控制台中打印默认格式值的原因。

您需要借助此方法从NSDate实例获取字符串值[your_dateformater stringFromDate:dateInstance]

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd";
NSString *datePart = @"2016-03-16";
NSDate *dateValue = [dateFormatter dateFromString:datePart];
NSLog(@"string convert into Date is - %@",[dateFormatter stringFromDate:dateValue]);

答案 2 :(得分:2)

日期格式化程序默认使用您的本地时区。 -[NSDate description]方法(%@调用的方法)使用UTC。这就是字符串不同的原因。