ios - 与 NSDate 混淆

标签 ios nsdate nstimezone

我正在尝试通过这种方式创建一个 NSDate 对象

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
   // [gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit  | NSMinuteCalendarUnit)fromDate:[NSDate date]];
    NSInteger day    = [weekdayComponents day];
    NSInteger month  = [weekdayComponents month];
    NSInteger year   = [weekdayComponents year];


    NSDateComponents *timeZoneComps=[[NSDateComponents alloc] init];
    [timeZoneComps setDay:day];
    [timeZoneComps setMonth:month];
    [timeZoneComps setYear:year];
    [timeZoneComps setHour:00];
    [timeZoneComps setMinute:00];
    [timeZoneComps setSecond:01];

    m_currentDate         = [gregorian dateFromComponents:timeZoneComps];

当我记录 currentDate 时,我得到了这个

"2014-07-07 06:00:01 +0000"

如果我将它保存到 plist 中,我会得到它

07-Jul-2014 11:30:01 am

如果我使用“UTC”作为时区

我明白了

"2014-07-07 00:00:01 +0000"

在 plist 中它显示为

07-Jul-2014 5:30:01 am

我不明白这是怎么回事,谁能帮我解决这个问题

我想知道,如果我不设置任何时区,将使用什么时区?

我们是否需要将 UTC 显式设置为时区,还是需要使用 systemTimeZone。

最佳答案

关于NSDate,您需要认识到的是,不存在诸如日、周、月、年、时区等之类的东西...

NSDate 纯粹是一个时间点。它没有关于它是什么时区等的信息...

实际上它只是一个数字。如果有帮助的话,您可以将其视为使用 UTC。

为您提供时区等信息的类有 NSCalendarNSDateFormatter 等...

我猜您所在的时区是 UTC+6?这就是为什么当您使用 00:00:01 创建日期并将其注销时,它会显示为 06:00:01。

这与NSDate无关。您在控制台中看到的是一个字符串。它是使用默认时区(您自己的)的日期对象的表示形式。

我必须看看你保存到 plist 的代码,但我怀疑这是同样的问题。您正在保存某些内容并假设它使用特定时区,但实际上并非如此。

关于ios - 与 NSDate 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24608953/

相关文章:

objective-c - 使用带时区的 NSDateFormatter 将 NSDate 转换为 NSString,无需 GMT 时间修改器

ios - URLSession 不适用于 URLCredential

ios - Apple HealthKit - 锻炼是否有相关的心率数据?

ios - 在 iOS 6 上发送全局触摸事件

android - "config.h file not found"怎么解决?从设备上的 native react 运行应用程序时?

ios - 静态 NSDate 变量在函数调用之间不断重置

iphone - 如何将 NSDateFormatter 更改为 "DD/MM/YYYY"?

ios - 检查给定的日期时间是否在 Objective C 中的其他两个日期时间之间

ios - 无法将 GMT 字符串日期转换为 Nsdate

iphone - 将 GMT 时间转换为本地时间