【问题标题】:Converting any date to local date issue将任何日期转换为本地日期问题
【发布时间】:2013-07-26 11:16:46
【问题描述】:

由于时区问题,我被困在 NSDateNSDateFormatter 的某个地方。

我只需要以 UTC(转换为 unix 时间)向服务器发送时间。

这是我正在做的几个步骤:

  1. 从日历中选择的日期应与当前时间相加并转换为 UTC。

  2. 将所选日期与当前日期进行比较。只是想知道所选日期是过去日期还是将来日期。 (根据过去/未来/当前日期进行的其他操作很少)。

我试过这段代码:

NSDate 的类别中:

-(NSDate *) toLocalTime{
    NSDate* sourceDate = self;
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];

    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

    NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];

    return destinationDate;
}

但是当我尝试将日期转换为本地时存在问题(有时我不确定当前时间是否在本地时区)。如果它们是 UTC,那么上述方法可以正常工作。

如果时间已经在本地时区,那么它会再次添加interval,我得到的时间不正确。

我没有想法,请帮助我。

任何想法都将受到高度赞赏。

【问题讨论】:

  • 希望对您有所帮助,请参考此链接。 stackoverflow.com/questions/7362199/…
  • 除非您绝对知道自己在做什么,否则您应该始终安排一个 NSDate 对象来表示 UTC。如果您使用设置为本地时区的 NSDateFormatter 将字符串转换为 NSDate,它将产生一个 UTC 日期——不需要“捏造”。要将字符串值从一个时区转换到另一个时区,最安全/最简单的方法是简单地转换为 NSDate 并返回,使用设置为两个不同时区的两个日期格式化程序。
  • "(有时我不确定当前时间是否在本地时区)" -- [NSDate date] 提供的“当前时间”总是 UTC(除非有人在电话上搞砸了时钟,在这种情况下,他们得到了应得的)。
  • (而且你应该完全放弃上述类别。正如我所说,你应该永远故意使 NSDate 代表 UTC 以外的时间。)

标签: objective-c macos cocoa nsdate nsdateformatter


【解决方案1】:

NSDate 表示自 1970 年 1 月 1 日以来的 UTC 时间。永远不要试图假装它是别的什么。永远不要把NSDate 想成是特定的当地时间。

因此,您需要的是日历中的日期 + 表示从今天午夜开始的时间的偏移量。

要获得今天凌晨 0:00 UTC,您首先需要 UTC 时区的公历。

NSTimeZone* utcTimeZone = [NSTimeZone timeZoneWithName:@"UTC"];
NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
[gregorian setTimeZone: utcTimeZone];

现在您使用日期组件来获取自 UTC 午夜以来的小时、分钟和秒

NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit |  NSSecondCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *comps = [gregorian components: unitFlags fromDate:date];

如果您的日历中的日期是 UTC 午夜,您可以获得午夜 UTC + 您的小时、分钟和秒,如下所示:

NSDate* theDateIWant = [gregorian dateByAddingComponents: comps 
                                                 toDate: midnightUTCDateFromCalendar
                                                options: 0];
NSLog(@"The final date is %@", theDateIWant);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多