NSDate - 将日期转换为 GMT

发布于 2024-08-13 18:18:33 字数 140 浏览 8 评论 0原文

我需要能够将 NSDate 值转换为 GMT 日期。

如何将 NSDate 值转换为 GMT 格式的 NSDate 值,而与 iPhone 设备使用的任何日期区域设置无关?

I need the ability to convert an NSDate value to a GMT Date.

How can I go about converting an NSDate value to a GMT formatted NSDate value, independent of whatever date locale settings the iPhone device is using?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

叹梦 2024-08-20 18:18:33
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";
        
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];
NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter release];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";
        
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];
NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter release];
倦话 2024-08-20 18:18:33

在 Cocoa 中处理时间可能很复杂。当您获取 NSDate 对象时,它位于本地时区。 [[NSTimeZone defaultTimeZone] secondaryFromGMT] 为您提供当前时区相对于 GMT 的偏移量。然后您可以执行以下操作:

NSDate *localDate = // get the date
NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; // You could also use the systemTimeZone method
NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneOffset;
NSDate *gmtDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];

现在 gmtDate 应该为您提供正确的 GMT 日期。为了显示它,请查看 NSDateFormatter,特别是 setDateStylesetTimeStyle 方法。您创建一个 NSDateFormatter,按照您想要的方式配置它,然后调用 stringFromDate: 来获取格式良好的字符串。

Working with time in Cocoa can be complicated. When you get an NSDate object, it's in the local time zone. [[NSTimeZone defaultTimeZone] secondsFromGMT] gives you the offset of the current time zone from GMT. Then you can do this:

NSDate *localDate = // get the date
NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; // You could also use the systemTimeZone method
NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneOffset;
NSDate *gmtDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];

Now gmtDate should have the correct date in GMT for you. In order to display it, look at NSDateFormatter, specifically the setDateStyle and setTimeStyle methods. You create an NSDateFormatter, configure it the way you want, and then call stringFromDate: to get a nicely formatted string.

巷子口的你 2024-08-20 18:18:33

霍华德的回答是正确的,请投票并接受

作为参考,我认为解释日期对象和本地化日期表示之间的区别很有用。

在许多编程语言中,日期对象用于表示唯一的时间点。忽略相对论参数,可以假设在任何情况下我们都可以定义一个时间点无论我们如何衡量时间,对每个人来说都是平等的。

如果我们可以为每个时间点构建一个唯一的标签,那么该标签就可以被传递并明确引用。 日期对象的目的是充当给定时间点的唯一通用标签

人们可以想出多种技术来构建这样的标签方案,并且每个日期对象如何选择这样做对于任何使用它们的人来说都是无关紧要的。

一个示例可能是使用通用事件的数字偏移量(自太阳爆炸以来的 X 秒)。

只有当我们希望获取一个时间点并将其序列化为人类可读的字符串时,我们才必须处理时区、区域设置等的复杂性......

(本地日期字符串) + ( 日期格式化程序) =>时间点

时间点 + (日期格式化程序) => (本地日期字符串

每个时间点都是通用的...不存在纽约时间点gmt时间点 ,只有当您将时间点转换为本地字符串(使用日期格式化程序)时,才会出现与时区的任何关联。

注意:我确信有很多关于这个问题的博客/文章,但我的 google foo 此时却让我失望。如果有人有热情扩展这个问题,请随意这样做。

Howard's Answer is correct and please vote it up and accept it.

For reference I think it is useful to explain the difference between date objects and localised date representations are.

In many programming languages date objects are used to represent unique points in time. Ignoring Relativistic arguments it can be assumed that at any instance we can define a point in time which is equal universally for every one, regardless of how we measure time.

If for each point in time we could construct a unique label, that label could be passed around and referenced unambiguously. The purpose of date objects is to act as a unique universal label for a given point in time.

One could come up with any number of techniques to construct such a labelling scheme and how each date object chooses to do so is immaterial to anyone using them.

An example may be to use a numeric offset from a universal event (X seconds since the sun exploded).

It is only when we wish to take a time point and serialize it into a human readable string that we must deal with the complexities of time zones, locales, etc...

(Local Date String) + (Date Formatter) => Time Point

Time Point + (Date Formatter) => (Local Date String)

Every time point is universal... there is no such thing as a new york time point, or gmt time point, only once you convert a time point to a local string (using a date formatter) does any association to a time zone appear.

Note: I'm sure there are many blogs/articles on this very issue, but my google foo is failing me at this hour. If anyone has the enthusiasm to expand on this issue please feel free to do so.

半衬遮猫 2024-08-20 18:18:33

斯威夫特4

//UTC or GMT ⟺ Local 

extension Date {

    // Convert local time to UTC (or GMT)
    func toGlobalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

    // Convert UTC (or GMT) to local time
    func toLocalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

}

Swift 4:

//UTC or GMT ⟺ Local 

extension Date {

    // Convert local time to UTC (or GMT)
    func toGlobalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

    // Convert UTC (or GMT) to local time
    func toLocalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

}
情独悲 2024-08-20 18:18:33

虽然 Alex 的答案是一个好的开始,但它没有处理 DST(夏令时),并添加了与参考日期之间不必要的转换。以下内容对我有用:

要从 localDate 转换为 GMT,考虑 DST:

NSDate *localDate = <<your local date>>
NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:localDate];
NSDate *gmtDate = [localDate dateByAddingTimeInterval:-timeZoneOffset]; // NOTE the "-" sign!

要从 GMT 日期转换为 localDate,考虑 DST:

NSDate *gmtDate  = <<your gmt date>>
NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:gmtDate];
NSDate *localDate = [gmtDate dateByAddingTimeInterval:timeZoneOffset];

一个小注意事项:我使用了 dateByAddingTimeInterval,仅适用于 iOS 4。如果您使用的是 OS 3 或更早版本,请使用 addTimerInterval。

While Alex's answer was a good start, it didn't deal with DST (daylight savings time) and added an unnecessary conversion to/from the reference date. The following works for me:

To convert from a localDate to GMT, taking DST into account:

NSDate *localDate = <<your local date>>
NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:localDate];
NSDate *gmtDate = [localDate dateByAddingTimeInterval:-timeZoneOffset]; // NOTE the "-" sign!

To convert from a GMT date to a localDate, taking DST into account:

NSDate *gmtDate  = <<your gmt date>>
NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:gmtDate];
NSDate *localDate = [gmtDate dateByAddingTimeInterval:timeZoneOffset];

One small note: I used dateByAddingTimeInterval, which is iOS 4 only. If you are on OS 3 or earlier, use addTimerInterval.

风吹短裙飘 2024-08-20 18:18:33

您是否尝试过查看 NSDateFormatter 的文档?

NSDateFormatter

NSDateFormatter 似乎有一些使用时区的方法,特别是

-setTimeZone:

我自己没有测试过,但我想如果您将 GMT 设置为最初以另一个时区表示的日期的时区,那么将显示经过正确调整以匹配新时区的日期。

Have you tried looking at the documentation for NSDateFormatter?

NSDateFormatter

NSDateFormatter appears to have some methods for playing with TimeZones, particularly

-setTimeZone:

I haven't tested it myself, but I imagine that if you set GMT as the timezone on a date that is originally represented in another timezone, it will display the date with the correct adjustments to match the new timezone.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文