【问题标题】:NSDate differs with different timezones in iOSNSDate 与 iOS 中的不同时区不同
【发布时间】:2014-06-26 06:49:35
【问题描述】:

我有一个日历应用程序,我在其中突出显示当前日期,

我按照以下步骤操作,目前我的设备时间是上午 11:59,

印度时区,我把它改成早上 9 点,然后我把时区改成圣何塞,

我的时间是 6 月 25 日晚上 9 点 34 分,现在在设备日历中显示为 6 月 25 日,但是

在我的应用中,它仍然显示 6 月 26 日。

我通过这种方式获取当前日期

-(void)initialize
{
    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];

   [m_dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

    m_dateFormatter.dateFormat = @"dd/MM/yyyy";

    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];   

}

所以,在这方面我需要你的帮助。

【问题讨论】:

  • 因为您明确使用UTC 时区?
  • 我删除了它,现在对于 san jose,它工作正常,在我的应用程序中显示 6 月 25 日,但现在如果我将时区更改为早于印度时区的澳大利亚,它应该显示给我6 月 26 日,但显示为 6 月 25 日。为什么会出现这个问题?
  • 你好@trojanfoe,你能看看我的评论吗

标签: ios nsdate nsdateformatter nscalendar nstimezone


【解决方案1】:

我认为[NSTimeZone systemTimeZone] 将始终为您提供设备检测(或设置)的当前时区。由于时区缓存在您的应用程序中,您还可以致电[NSTimeZone resetSystemTimeZone] 以确保信息是最新的。所以,在你的代码中:

[NSTimeZone resetSystemTimeZone]; [m_dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];

【讨论】:

  • 嘿@spassas,因为我通过将时区设置为 UTC 创建了我的日历,我现在无法更改,因为它会破坏一些东西,我们可以做些什么,将时区保持为 UTC。
  • 嗯,我不确定我是否跟随。您正在尝试获取当前时区中的当前日期,对吗?所以你不能明确使用UTC timezone...如果我可能会问,你害怕打破什么?
  • 我以前版本的应用程序使用了 UTC 时区。所以现在如果我使用系统时区,那么我会得到不同的时间。所以现在以前的日期将是 UTC,新的日期将是系统时区,所以时间不同
  • 我不明白这会如何导致问题。只需检索当前时区,获取时区中的日/月,然后在您的应用中突出显示相应的单元格。为什么这会破坏任何以前的版本?
  • 我会尝试并回复您。
猜你喜欢
  • 2011-09-17
  • 2014-07-13
  • 1970-01-01
  • 2013-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-23
相关资源
最近更新 更多