【问题标题】:Need information on printing [NSDate date]需要有关打印的信息 [NSDate 日期]
【发布时间】:2016-01-08 14:41:19
【问题描述】:

当我打印日期时

//getting the current date and time
self.date = [NSDate date];
NSLog(@"%@",date);

我得到的日期是正确的,但时间延迟了 6 小时。我的系统时间是正确的。

【问题讨论】:

  • [NDate date] 方法根据设备的区域设置返回当前日期和时间。如果要设置为不同的语言环境,则必须使用“descriptionWithLocale”手动设置它,它使用给定的语言环境返回接收者的字符串表示形式。

标签: ios nsdate


【解决方案1】:

试试这个

NSLocale* currentLoc = [NSLocale currentLocale];
NSLog(@"%@",[[NSDate date] descriptionWithLocale:currentLoc]); 

【讨论】:

  • [[NSDate date] descriptionWithLocale: [NSLocale currentLocale ]] 使单行更容易复制
  • 现在你应该使用 [NSLocale autoupdatingCurrentLocale]
【解决方案2】:

利用NSDateFormatter

NSDate *today = [NSDate date];

//Create the dateformatter object
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

//Set the required date format
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

//Get the string date
NSString *dateString = [dateFormatter stringFromDate:today];

//Display on the console
NSLog(dateString);

【讨论】:

  • 请注意,dateFormatString 是错误的。它还将打印月份作为时间的一部分。 SS 也代表其他东西。应该是@"yyyy-MM-dd HH:mm:ss"
  • @luk2302:非常感谢。我已经更新了我的答案。
【解决方案3】:

在调试器中记录 NSDate 有点误导,因为它会为您提供特定时区的日历日和时间 - UTC / GMT。然而,NSDate 没有固有的时区或与人类如何感知和思考日期的任何固有关系。相反,它是一个时间戳。 NSDateComponentsNSTimeZoneNSDateFormatter 等类都存在以提供人类上下文和格式。

因此,您看到的是格式化为特定格式和 UTC 时区的时间戳,这就是 NSDate 在调试器或控制台中打印时始终显示的方式。如果您要计算 UTC 和您自己的时区之间的时区偏移量,您会发现日期代表的是您给它的时间戳,而不是一个多小时。

【讨论】:

    【解决方案4】:

    您可以设置当前时区以自定义日期格式。

    此链接可以帮助: https://stackoverflow.com/a/7213629/456471

    【讨论】:

      【解决方案5】:

      默认的日期字符串表示可能会将日期格式化为 UTC,而不是您的本地时区(未定义它将使用的确切格式,并且可能会因版本而异,因此您不应依赖它)。如果您需要以特定格式(或特定时区,包括本地时区)格式化日期,则应使用 NSDateFormatter 类;有关详细信息,请参阅 Data Formatting GuideNSDateFormatter Class Reference

      【讨论】:

        猜你喜欢
        • 2011-02-23
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        • 2014-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多