【问题标题】:Converting NSString to NSDate is generating wrong value将 NSString 转换为 NSDate 会生成错误的值
【发布时间】:2013-03-29 09:30:36
【问题描述】:

目前我有一个 NSString 值,其中包含以下日期作为当前日期

(lldb) po self.currentDate
(NSString *) $5 = 0x002ca8d0 2013-03-29

但是当我将此 NSString 转换为 NSDate 时,它​​显示的值错误

NSDate *myCurrentDate  = [dateFormatterForCurrentDate dateFromString:self.currentDate];

(lldb) po myCurrentDate
(NSDate *) $4 = 0x002cf030 2013-03-28 18:30:00 +0000

【问题讨论】:

标签: ios objective-c


【解决方案1】:

尝试使用此代码,以考虑本地时区....

NSDateFormatter *dateFormatterForCurrentDate = [[NSDateFormatter alloc] init];
[dateFormatterForCurrentDate setDateFormat:@"yyyy-MM-dd"];
[dateFormatterForCurrentDate setTimeZone:[NSTimeZone localTimeZone]];
NSDate *myCurrentDate  = [dateFormatterForCurrentDate dateFromString:self.currentDate];

希望这有帮助...

【讨论】:

    【解决方案2】:

    设置此日期格式:

        [dateFormatterForCurrentDate setDateFormat:@"yyyy-MM-dd"];
    

    同时检查 developer.apple.com 中的Date Formatters

    可能对你有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-21
      • 1970-01-01
      • 2011-04-24
      • 2017-04-23
      • 2021-09-11
      相关资源
      最近更新 更多