iOS Swift - 获取当前本地时间和日期时间戳

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

iOS Swift - Get the Current Local Time and Date Timestamp

iosswiftdatefirebasetimestamp

提问by TSM

I'm trying to make an attendance app and I am really confused about date and time in iOS and Firebase.

我正在尝试制作一个考勤应用程序,但我对 iOS 和 Firebase 中的日期和时间感到非常困惑。

I use date as Key, this is the structure of my Firebase database.

我使用日期作为 Key,这是我的 Firebase 数据库的结构。

--Employees
  --Unique_ID
     --Details
          Name: John
     --Attendance
          --dateToday
              Timein: 8:00 AM
              Timeout: 5:00 PM
              BreakStart: 12:00 PM
              BreakFinish: 1:00 PM

This is my code to get the date timestamp I used as Key

这是我用于获取用作 Key 的日期时间戳的代码

 override func viewDidLoad() {
     super.viewDidLoad()

     let now = NSDate()
     let nowTimeStamp = self.getCurrentTimeStampWOMiliseconds(dateToConvert: now)

     // I save this dateToday as Key in Firebase
     dateToday = nowTimeStamp
}


func getCurrentTimeStampWOMiliseconds(dateToConvert: NSDate) -> String {
    let objDateformat: DateFormatter = DateFormatter()
    objDateformat.dateFormat = "yyyy-MM-dd"
    let strTime: String = objDateformat.string(from: dateToConvert as Date)
    let objUTCDate: NSDate = objDateformat.date(from: strTime)! as NSDate
    let milliseconds: Int64 = Int64(objUTCDate.timeIntervalSince1970)
    let strTimeStamp: String = "\(milliseconds)"
    return strTimeStamp
}

But when I convert it back to date I get 2017-09-22 16:00:00 +0000, which is wrong because it is 23rd of September in my location.

但是当我将其转换回日期时,我得到 2017-09-22 16:00:00 +0000,这是错误的,因为我所在的位置是 9 月 23 日。

What is the right code to use so that I can get the correct date timestamp and time timestamp?

使用什么正确的代码才能获得正确的日期时间戳和时间时间戳?

回答by Satish Babariya

For saving Current time to firebase database I use Unic Epoch Conversation:

为了将当前时间保存到 firebase 数据库,我使用了 Unic Epoch Conversation:

let timestamp = NSDate().timeIntervalSince1970

and For Decoding Unix Epoch time to Date().

和用于解码 Unix Epoch 时间到 Date()。

let myTimeInterval = TimeInterval(timestamp)
let time = NSDate(timeIntervalSince1970: TimeInterval(myTimeInterval))

回答by lenooh

If you just want the unix timestamp, create an extension:

如果您只想要 unix 时间戳,请创建一个扩展:

extension Date {
    func currentTimeMillis() -> Int64 {
        return Int64(self.timeIntervalSince1970 * 1000)
    }
}

Then you can use it just like in other programming languages:

然后你可以像在其他编程语言中一样使用它:

let timestamp = Date().currentTimeMillis()

回答by Alex

First I would recommend you to store your timestamp as a NSNumberin your Firebase Database, instead of storing it as a String.

首先,我建议您将时间戳作为 a 存储NSNumber在 Firebase 数据库中,而不是将其存储为String.

Another thing worth mentioning here, is that if you want to manipulate dates with Swift, you'd better use Dateinstead of NSDate, except if you're interacting with some Obj-C code in your app.

这里值得一提的另一件事是,如果您想用 Swift 操作日期,最好使用Date代替NSDate,除非您正在与应用程序中的某些 Obj-C 代码进行交互。

You can of course use both, but the Documentation states:

您当然可以同时使用两者,但文档说明:

Date bridges to the NSDate class. You can use these interchangeably in code that interacts with Objective-C APIs.

Date 连接到 NSDate 类。您可以在与 Objective-C API 交互的代码中交替使用这些。

Now to answer your question, I think the problem here is because of the timezone.

现在回答你的问题,我认为这里的问题是因为时区。

For example if you print(Date()), as for now, you would get:

例如,如果你print(Date())现在,你会得到:

2017-09-23 06:59:34 +0000

This is the Greenwich Mean Time (GMT).

这是格林威治标准时间 (GMT)。

So depending on where you are located (or where your users are located) you need to adjust the timezone before (or after, when you try to access the data for example) storing your Date:

因此,根据您所在的位置(或您的用户所在的位置),您需要在存储以下内容之前(或之后,当您尝试访问数据时)调整时区Date

    let now = Date()

    let formatter = DateFormatter()

    formatter.timeZone = TimeZone.current

    formatter.dateFormat = "yyyy-MM-dd HH:mm"

    let dateString = formatter.string(from: now)

Then you have your properly formatted String, reflecting the current time at your location, and you're free to do whatever you want with it :) (convert it to a Date/ NSNumber, or store it directly as a Stringin the database..)

然后你有你的正确格式String,反映你所在位置的当前时间,你可以自由地用它做任何你想做的事情:)(将它转换为Date/ NSNumber,或直接将它作为 a 存储String在数据库中..)

回答by dengST30

in Swift 5

斯威夫特 5

extension Date {
    static var currentTimeStamp: Int64{
        return Int64(Date().timeIntervalSince1970 * 1000)
    }
}

call like this:

像这样调用:

let timeStamp = Date.currentTimeStamp
print(timeStamp)

Thanks @lenooh

谢谢@lenooh

回答by User558

The simple way to create Current TimeStamp. like below,

创建当前时间戳的简单方法。像下面,

func generateCurrentTimeStamp () -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy_MM_dd_hh_mm_ss"
    return (formatter.string(from: Date()) as NSString) as String
}

回答by Jesper Samuelsson

If you code for iOS 13.0 or later and want a timestamp, then you can use:

如果您为 iOS 13.0 或更高版本编码并想要时间戳,那么您可以使用:

let currentDate = NSDate.now

回答by bsod

When we convert a UTC timestamp (2017-11-06 20:15:33 -08:00) into a Dateobject, the time zone is zeroed out to GMT. For calculating time intervals, this isn't an issue, but it can be for rendering times in the UI.

当我们将 UTC 时间戳 ( 2017-11-06 20:15:33 -08:00) 转换为Date对象时,时区将归零为 GMT。对于计算时间间隔,这不是问题,但它可以用于 UI 中的渲染时间。

I favor the RFC3339 format (2017-11-06T20:15:33-08:00) for its universality. The date format in Swift is yyyy-MM-dd'T'HH:mm:ssXXXXXbut RFC3339 allows us to take advantage of the ISO8601DateFormatter:

我赞成 RFC3339 格式 ( 2017-11-06T20:15:33-08:00) 的通用性。Swift 中的日期格式是yyyy-MM-dd'T'HH:mm:ssXXXXX但 RFC3339 允许我们利用ISO8601DateFormatter

func getDateFromUTC(RFC3339: String) -> Date? {
    let formatter = ISO8601DateFormatter()
    return formatter.date(from: RFC3339)
}

RFC3339 also makes time-zone extraction simple:

RFC3339 还使时区提取变得简单:

func getTimeZoneFromUTC(RFC3339: String) -> TimeZone? {

    switch RFC3339.suffix(6) {

    case "+05:30":
        return TimeZone(identifier: "Asia/Kolkata")

    case "+05:45":
        return TimeZone(identifier: "Asia/Kathmandu")

    default:
        return nil

    }

}

There are 37 or so other time zones we'd have to account for and it's up to you to determine which ones, because there is no definitive list. Some standards count fewer time zones, some more. Most time zones break on the hour, some on the half hour, some on 0:45, some on 0:15.

我们必须考虑 37 个左右的其他时区,由您决定哪些时区,因为没有明确的列表。有些标准计算较少的时区,有些则更多。大多数时区在整点,有些在半小时,有些在0:45,有些在0:15

We can combine the two methods above into something like this:

我们可以将上面的两种方法组合成这样:

func getFormattedDateFromUTC(RFC3339: String) -> String? {

    guard let date = getDateFromUTC(RFC3339: RFC3339),
        let timeZone = getTimeZoneFromUTC(RFC3339: RFC3339) else {
            return nil
    }

    let formatter = DateFormatter()
    formatter.dateFormat = "h:mma EEE, MMM d yyyy"
    formatter.amSymbol = "AM"
    formatter.pmSymbol = "PM"
    formatter.timeZone = timeZone // preserve local time zone
    return formatter.string(from: date)

}

And so the string "2018-11-06T17:00:00+05:45", which represents 5:00PM somewhere in Kathmandu, will print 5:00PM Tue, Nov 6 2018, displaying the local time, regardless of where the machine is.

因此"2018-11-06T17:00:00+05:45",代表加德满都某处下午 5:00的字符串将打印5:00PM Tue, Nov 6 2018,显示当地时间,而不管机器在哪里。

As an aside, I recommend storing dates as strings remotely (including Firestore which has a native date object) because, I think, remote data should agnostic to create as little friction between servers and clients as possible.

顺便说一句,我建议将日期远程存储为字符串(包括具有本机日期对象的 Firestore),因为我认为远程数据应该是不可知的,以尽可能减少服务器和客户端之间的摩擦。

回答by MacacoAzul

you can even create a function to return different time stamps depending on your necessity:

您甚至可以根据需要创建一个函数来返回不同的时间戳:

func dataatual(_ tipo:Int) -> String {
        let date = Date()
        let formatter = DateFormatter()
        if tipo == 1{
            formatter.dateFormat = "dd/MM/yyyy"
        } else if tipo == 2{
            formatter.dateFormat = "yyyy-MM-dd HH:mm"
        } else {
            formatter.dateFormat = "dd-MM-yyyy"
        }

        return formatter.string(from: date)
    }