ios 从 NSDate 对象获取 UTC 时间和本地时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24917483/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:31:13  来源:igfitidea点击:

Get UTC time and local time from NSDate object

iosobjective-cswiftnsdate

提问by p0lAris

In objective-c, the following code results in the UTC date time information using the dateAPI.

在objective-c 中,以下代码使用dateAPI生成UTC 日期时间信息。

NSDate *currentUTCDate = [NSDate date]

In Swift however,

然而,在 Swift 中,

let date = NSDate.date()

results in local date and time.

结果是本地日期和时间。

I have two questions:

我有两个问题:

  1. How can I get UTC time and local time (well dategives local time) in NSDateobjects.
  2. How can I get precision for seconds from the NSDateobject.
  1. 如何dateNSDate对象中获取 UTC 时间和本地时间(很好地给出本地时间)。
  2. 如何从NSDate对象获得几秒钟的精度。

EDIT 1: Thanks for all the inputs but I am not looking for NSDateFormatterobjects or string values. I am simply looking for NSDate objects (however we cook them up but that's the requirement).
See point 1.

编辑 1:感谢所有输入,但我不是在寻找NSDateFormatter对象或字符串值。我只是在寻找 NSDate 对象(但是我们将它们煮熟,但这就是要求)。
见第 1 点。

采纳答案by RaffAl

The documentation says that the datemethod returns a new date set to the current date and time regardless of the language used.

文档说date无论使用什么语言,该方法都会返回一个设置为当前日期和时间的新日期。

The issue probably sits somewhere where you present the date using NSDateFormatter. NSDateis just a point on a time line. There is no time zones when talking about NSDate. I made a test.

问题可能出在您使用NSDateFormatter. NSDate只是时间线上的一个点。谈论时没有时区NSDate。我做了一个测试。

Swift

迅速

print(NSDate())

Output: 2014-07-23 17:56:45 +0000

输出: 2014-07-23 17:56:45 +0000

Objective-C

目标-C

NSLog(@"%@", [NSDate date]);

Output: 2014-07-23 17:58:15 +0000

输出: 2014-07-23 17:58:15 +0000

Result - No difference.

结果 -没有区别。

回答by Steven Fisher

NSDateis a specific point in time without a time zone. Think of it as the number of seconds that have passed since a reference date. How many seconds have passed in one time zone vs. another since a particular reference date? The answer is the same.

NSDate没有时区的特定时间点。将其视为自参考日期以来经过的秒数。自特定参考日期以来,一个时区与另一个时区已经过去了多少秒?答案是一样的。

Depending on how you outputthat date (including looking at the debugger), you may get an answer in a different time zone.

根据您输出该日期的方式(包括查看调试器),您可能会在不同的时区得到答案。

If they ran at the same moment, the values of these are the same. They're both the number of seconds since the reference date, which may be formatted on outputto UTC or local time. Within the date variable, they're both UTC.

如果它们同时运行,它们的值是相同的。它们都是自参考日期以来的秒数,可以在输出到 UTC 或本地时间时进行格式化。在日期变量中,它们都是 UTC。

Objective-C:

目标-C:

NSDate *UTCDate = [NSDate date]

Swift:

迅速:

let UTCDate = NSDate.date()

To explain this, we can use a NSDateFormatter in a playground:

为了解释这一点,我们可以在 Playground 中使用 NSDateFormatter:

import UIKit

let date = NSDate.date()
    // "Jul 23, 2014, 11:01 AM" <-- looks local without seconds. But:

var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
let defaultTimeZoneStr = formatter.stringFromDate(date)
    // "2014-07-23 11:01:35 -0700" <-- same date, local, but with seconds
formatter.timeZone = NSTimeZone(abbreviation: "UTC")
let utcTimeZoneStr = formatter.stringFromDate(date)
    // "2014-07-23 18:01:41 +0000" <-- same date, now in UTC

The date outputvaries, but the date is constant. This is exactly what you're saying. There's no such thing as a local NSDate.

日期输出会有所不同,但日期是恒定的。这正是你要说的。没有本地 NSDate 这样的东西。

As for how to get microseconds out, you can use this (put it at the bottom of the same playground):

至于如何取出微秒,可以用这个(放在同一个playground的底部):

let seconds = date.timeIntervalSince1970
let microseconds = Int(seconds * 1000) % 1000 // chops off seconds

To compare two dates, you can use date.compare(otherDate).

要比较两个日期,您可以使用date.compare(otherDate).

回答by Leo Dabus

Xcode 9 ? Swift 4(also works Swift 3.x)

Xcode 9 ? Swift 4(也适用于 Swift 3.x)

extension Formatter {
    // create static date formatters for your date representations
    static let preciseLocalTime: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "HH:mm:ss.SSS"
        return formatter
    }()
    static let preciseGMTTime: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.dateFormat = "HH:mm:ss.SSS"
        return formatter
    }()
}


extension Date {
    // you can create a read-only computed property to return just the nanoseconds from your date time
    var nanosecond: Int { return Calendar.current.component(.nanosecond,  from: self)   }
    // the same for your local time
    var preciseLocalTime: String {
        return Formatter.preciseLocalTime.string(for: self) ?? ""
    }
    // or GMT time
    var preciseGMTTime: String {
        return Formatter.preciseGMTTime.string(for: self) ?? ""
    }
}


Playground testing

游乐场测试

Date().preciseLocalTime // "09:13:17.385"  GMT-3
Date().preciseGMTTime   // "12:13:17.386"  GMT
Date().nanosecond       // 386268973

This might help you also formatting your dates:

这可能有助于您格式化日期:

enter image description here

在此处输入图片说明

回答by Daij-Djan

a date is independant of any timezone, so use a Dateformatter and attach a timezone for display:

日期与任何时区无关,因此请使用 Dateformatter 并附加时区以进行显示:

swift:

迅速:

let date = NSDate()
let dateFormatter = NSDateFormatter()
let timeZone = NSTimeZone(name: "UTC")

dateFormatter.timeZone = timeZone

println(dateFormatter.stringFromDate(date))

objC:

对象:

NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];

[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeZone:timeZone];       
NSLog(@"%@", [dateFormatter stringFromDate:date]);

回答by abhimuralidharan

let date = Date() 
print(date) // printed date is UTC 

If you are using playground, use a print statement to check the time. Playground shows local time until you print it. Do not depend on the right side panel of playground. enter image description here

如果您正在使用playground,请使用打印语句来检查时间。Playground 显示当地时间,直到您打印出来。不要依赖操场的右侧面板。 在此处输入图片说明

This code gives date in UTC. If you need the local time, you should call the following extension with timezone as Timezone.current

此代码以 UTC 格式给出日期。如果您需要本地时间,您应该使用时区调用以下扩展名Timezone.current

 extension Date {

   var currentUTCTimeZoneDate: String {
        let formatter = DateFormatter()
        formatter.timeZone = TimeZone(identifier: "UTC")
        formatter.amSymbol = "AM"
        formatter.pmSymbol = "PM"
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

        return formatter.string(from: self)
    }
}

For UTC time, use it like: Date().currentUTCTimeZoneDate

对于 UTC 时间,像这样使用它: Date().currentUTCTimeZoneDate

回答by Ali

At the moment (with the latest changes to Swift), NSDate.date()is not longer available.

目前(随着 Swift 的最新变化),NSDate.date()不再可用。

Instead you just need to initialize NSDateand it gets the current date and time.
To try it, in a playground:

相反,您只需要初始化NSDate并获取当前日期和时间。
尝试一下,在操场上:

var d = NSDate()
d

and you will get:

你会得到:

Oct 22, 2014, 12:20 PM"  

回答by Piyush Sanepara

Swift 3

斯威夫特 3

You can get Date based on your current timezone from UTC

您可以根据当前时区从 UTC 获取日期

extension Date {
    func currentTimeZoneDate() -> String {
        let dtf = DateFormatter()
        dtf.timeZone = TimeZone.current
        dtf.dateFormat = "yyyy-MM-dd HH:mm:ss"

        return dtf.string(from: self)
    }
}

Call like this:

像这样调用:

Date().currentTimeZoneDate()

回答by fujianjin6471

My Xcode Version 6.1.1 (6A2008a)

我的 Xcode 版本 6.1.1 (6A2008a)

In playground, test like this:

在操场上,像这样测试:

// I'm in East Timezone 8
let x = NSDate() //Output:"Dec 29, 2014, 11:37 AM"
let y = NSDate.init() //Output:"Dec 29, 2014, 11:37 AM"
println(x) //Output:"2014-12-29 03:37:24 +0000"


// seconds since 2001
x.hash //Output:441,517,044
x.hashValue //Output:441,517,044
x.timeIntervalSinceReferenceDate //Output:441,517,044.875367

// seconds since 1970
x.timeIntervalSince1970 //Output:1,419,824,244.87537

回答by Usuf

I found an easier way to get UTC in Swift4. Put this code in playground

我找到了一种在 Swift4 中获取 UTC 的更简单方法。将此代码放在操场上

let date = Date() 
*//"Mar 15, 2018 at 4:01 PM"*

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

let newDate = dateFormatter.string(from: date) 
*//"2018-03-15 21:05:04 +0000"*

回答by Asad Ali Choudhry

In addition to other answers, you can write an extension for Date class to get formatted Data in specific TimeZone to make it as utility function for future use. Like

除了其他答案之外,您还可以为 Date 类编写扩展以获取特定 TimeZone 中的格式化数据,使其作为实用函数以备将来使用。喜欢

 extension Date {

 func dateInTimeZone(timeZoneIdentifier: String, dateFormat: String) -> String  {
 let dtf = DateFormatter()
 dtf.timeZone = TimeZone(identifier: timeZoneIdentifier)
 dtf.dateFormat = dateFormat

 return dtf.string(from: self)
 }
}

Now you can call it like

现在你可以这样称呼它

 Date().dateInTimeZone(timeZoneIdentifier: "UTC", dateFormat: "yyyy-MM-dd HH:mm:ss");