iphone - 从调整时区的 NSDate 获取 NSDate

标签 iphone ios timezone nsdate locale

我有一个 NSDate 对象。假设它代表“1-10-2011”

NSDate *date = [df dateFromString:@"2011-10-01 00:00:00"];

由于我所在的时区,该日期转换为“2011-09-30 22:00:00”。

问题:如何在我的本地时区中获取表示“2011-10-01 00:00:00”的新日期对象?

最佳答案

NSDate 只代表一个绝对时间点。它没有时区或日历的概念。当您创建一个 NSDate 实例时,它只是自格林威治标准时间 2001 年 1 月 1 日以来的秒数!无论您是在纽约、东京、巴塞罗那还是耶路撒冷,都没有关系。

在您的示例中,您实例化了基于 GMT 的 NSDate,但是 [date description](在 NSLog 中使用)将其转换为您的本地时间。你有不匹配的地方。

所以有两部分需要考虑:

1。使用 NSCalendar 和 NSTimeZone 创建 NSDate

如果您手动创建日期,则应指定日历(公历 2012 年,希伯来语 5772)和时区(伦敦时间下午 22 点,悉尼时间早上 7 点)。

// Use the user's current calendar and time zone
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone: [NSTimeZone systemTimeZone]];

// Specify the date components manually (year, month, day, hour, minutes, etc.)
NSDateComponents *timeZoneComps=[[NSDateComponents alloc] init];
[timeZoneComps setHour:22];
[timeZoneComps setMinute:0];
[timeZoneComps setSecond:0];
// ... year, month, ...

// transform the date compoments into a date, based on current calendar settings
NSDate *date = [calendar dateFromComponents:timeZoneComps];

此时 date 存储代表当前日历的准确时间点(以秒为单位)。

2。使用 NSDateFormatter 输出 NSDate

对于 NSDate 的受控输出,您需要 NSDateFormatter,它用于将日期转换为字符串。

基于苹果 NSDateFormatter Class Reference文档

There are many attributes you can get and set on a style date formatter, ... You are encouraged, however, not to change individual settings. Instead you should accept the default settings established on initialization and specify the format using setDateStyle:, setTimeStyle:

这对于输出特别重要,每个语言环境的输出都不同。默认情况下 NSDateFormatter 观察当前用户的区域设置。因此,相同的 NSDate 可能是 22.11.2011 18:33:19,或 Nov 22, 2011 6:33:19 PM,或 2011-11-22下午 6:33:19 甚至 २२-११-२०११ ६:३३:१९ अपराह्,所有这些都用于相同的输入和相同的代码。

代码:

//  NSDate *date -> NSString *dateString 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];

// Medium style date, short style time => "Nov 23, 1937 3:30pm"
NSString *dateString = [dateFormatter stringFromDate:date];

或者您可以使用类方法对其进行转换 localizedStringFromDate:dateStyle:timeStyle:

我希望这能澄清问题。

关于iphone - 从调整时区的 NSDate 获取 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7485493/

相关文章:

ios - Swift (iOS) - PickerView 未被 HTTP GET 请求填充

android - MySQL 到 Sqlite 从 PHP 同步到移动应用程序 (iOS/Android)

javascript - Moment JS - 如何从另一个时区获取时间

ios - 如何从时间字符串获取时区

ios - 设置包未显示在 iPhone 设置中

ios - swift 3 : Ambiguous use of mutablecopy

iphone - 使用 JSON 将 NSDictionary 保存到 MySQL

ios - 转到另一个 Storyboard,但导航 Controller 仍然可见

ios - 为什么我不能使 HttpWebRequest 与 NTLM 身份验证一起使用

postgresql - 我应该在 PostgreSQL 数据库中选择哪种时间戳类型?