【问题标题】:I can't figure out why my code for using the local timezone for the phone doesn't work我不知道为什么我的电话使用本地时区的代码不起作用
【发布时间】:2013-11-07 08:28:08
【问题描述】:

我正在编写一个使用 UINotifications 的应用程序,我的代码可用于通知,但无法获取正确的时区。

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

// Get the current date
NSDate *pickerDate = [self.datePicker date];
// Break the date up into components
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSTimeZoneCalendarUnit)
                                               fromDate:pickerDate];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
                                               fromDate:pickerDate];

我很确定我在上面的 NSDateComponents 中正确理解了它

// Set up the fire time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];

我很确定应该为当前手机位置设置时区

[dateComps setTimeZone:[dateComponents timeZone]];

[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];

NSLog(@"%@",[NSString stringWithFormat:@"%@",itemDate]);

我尝试将 itemDate 转储到日志文件中,我得到的结果看起来像 GMT

2013-11-07 00:24:14.559 IMOB[796:60b] 2013-11-07 08:23:56 +0000

正如您在日志文件行开头的时间戳中看到的那样,它显示正确的时间是早上 12:24,但输出显示为 08:23

怎么了

【问题讨论】:

    标签: ios objective-c timezone nsdate


    【解决方案1】:

    NSDate 对象始终是 UTC。使用NSDateFormatter 根据您的语言环境记录值。

    [NSDateFormatter localizedStringFromDate:dateStyle:timeStyle:] 非常好用。

    【讨论】:

      猜你喜欢
      • 2020-09-19
      • 2014-01-17
      • 2020-02-05
      • 1970-01-01
      • 2021-10-19
      • 2021-03-11
      • 2019-05-21
      • 2016-08-25
      • 1970-01-01
      相关资源
      最近更新 更多