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

Ban*_*ore -1 objective-c nsdate nsdateformatter ios

我有这个日期格式为"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 
Run Code Online (Sandbox Code Playgroud)

Pau*_*w11 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]) ,您将在当前时区看到日期.

请注意,虽然description方法和相关方法descriptionWithCalendarFormat仅用于调试,但您应该使用NSDateFormatter将日期转换为字符串.iOS_Binod的答案显示了一种可以做到这一点的方法.