ios Objective-C 将 NSDate 设置为当前 UTC
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2615833/
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
Objective-C setting NSDate to current UTC
提问by Brodie
Is there an easy way to init an NSDate
with the current UTC date/time?
有没有一种简单的方法可以NSDate
用当前的 UTC 日期/时间来初始化?
回答by jessecurry
[NSDate date];
[NSDate date];
You may want to create a category that does something like this:
您可能想要创建一个执行以下操作的类别:
-(NSString *)getUTCFormateDate:(NSDate *)localDate
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:localDate];
[dateFormatter release];
return dateString;
}
回答by rcw3
NSDate is a reference to an interval from an absolute reference date, January 1, 2001 00:00 GMT. So the class method [NSDate date] will return a representation of that interval. To present that data in a textual format in UTC, just use the NSDateFormatter with the appropriate NSTimeZone (UTC) to render as needed.
NSDate 是对绝对参考日期(格林威治标准时间 2001 年 1 月 1 日 00:00)的间隔的引用。因此类方法 [NSDate date] 将返回该间隔的表示。要在 UTC 中以文本格式显示该数据,只需使用 NSDateFormatter 和适当的 NSTimeZone (UTC) 来根据需要呈现。
回答by Tikhonov Alexander
NSDateobjects encapsulate a single point in time, independent of any particular calendrical system or time zone. Date objects are immutable, representing an invariant time interval relative to an absolute reference date (00:00:00 UTCon 1 January 2001).
NSDate对象封装了单个时间点,独立于任何特定的日历系统或时区。日期对象是不可变的,表示相对于绝对参考日期(2001 年 1 月 1 日00:00:00 UTC)的不变时间间隔。
Swift version:
迅捷版:
extension NSDate {
func getUTCFormateDate() -> String {
let dateFormatter = NSDateFormatter()
let timeZone = NSTimeZone(name: "UTC")
dateFormatter.timeZone = timeZone
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter.stringFromDate(self)
}
}