ios NSDate - 将日期转换为 GMT
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1862905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSDate - Convert Date to GMT
提问by Mick
I need the ability to convert an NSDate
value to a GMT Date.
我需要能够将NSDate
值转换为 GMT 日期。
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?
如何将NSDate
值转换为 GMT 格式的NSDate
值,而与 iPhone 设备使用的日期区域设置无关?
回答by Howard
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];
回答by Alex
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:
在 Cocoa 中处理时间可能很复杂。当您获得一个NSDate
对象时,它位于本地时区。[[NSTimeZone defaultTimeZone] secondsFromGMT]
为您提供当前时区与 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];
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.
现在gmtDate
应该为您提供正确的格林威治标准时间日期。为了显示它,请查看NSDateFormatter
,特别是setDateStyle
和setTimeStyle
方法。您创建一个NSDateFormatter
,按照您想要的方式对其进行配置,然后调用stringFromDate:
以获取格式良好的字符串。
回答by Akusete
Howard's Answeris 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 Relativisticarguments 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).
一个例子可能是使用来自普遍事件的数字偏移量(自太阳爆炸以来的 X 秒)。
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.
注意:我确定有很多关于这个问题的博客/文章,但是我的 google foo 在这个时候让我失望了。如果有人有热情扩展这个问题,请随时这样做。
回答by Krunal
Swift 4:
斯威夫特 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)
}
}
回答by thevoid
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:
虽然亚历克斯的回答是一个好的开始,但它没有处理 DST(夏令时)并添加了与参考日期之间的不必要转换。以下对我有用:
To convert from a localDate to GMT, taking DST into account:
要从 localDate 转换为 GMT,请考虑 DST:
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:
要将 GMT 日期转换为 localDate,请考虑 DST:
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.
一个小提示:我使用了 dateByAddingTimeInterval,它仅适用于 iOS 4。如果您使用的是 OS 3 或更早版本,请使用 addTimerInterval。
回答by Jasarien
Have you tried looking at the documentation for NSDateFormatter?
您是否尝试查看 NSDateFormatter 的文档?
NSDateFormatter appears to have some methods for playing with TimeZones, particularly
NSDateFormatter 似乎有一些使用 TimeZones 的方法,特别是
-setTimeZone:
-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.
我自己没有测试过,但我想如果您将 GMT 设置为最初以另一个时区表示的日期的时区,它将显示具有正确调整的日期以匹配新时区。