我有一个 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/