Swift - Get local date and time

前端 未结 10 656
挽巷
挽巷 2020-12-17 08:51

How can I get local date and time in Swift?

let last_login = String(NSDate.date())
10条回答
  •  [愿得一人]
    2020-12-17 09:19

    To get back the most common string formats (when dealing with queries and databases):

    Swift 4

    2019-01-09T01:07:04Z (RFC3339 in GMT/Zulu time)

    let f = ISO8601DateFormatter()
    f.formatOptions = [.withInternetDateTime]
    let s = f.string(from: Date())
    

    2019-01-08T17:04:16-08:00 (RFC3339 accounting for local time zone)

    let f = ISO8601DateFormatter()
    f.formatOptions = [.withInternetDateTime]
    f.timeZone = TimeZone.current
    let s = f.string(from: Date())
    

    2019-01-09 (standard date stamp in GMT/Zulu time)

    let f = ISO8601DateFormatter()
    f.formatOptions = [.withFullDate, .withDashSeparatorInDate]
    let s = f.string(from: Date())
    

    2019-01-08 (standard date stamp accounting for local time zone)

    let f = ISO8601DateFormatter()
    f.formatOptions = [.withFullDate, .withDashSeparatorInDate]
    f.timeZone = TimeZone.current
    let s = f.string(from: Date())
    

    All four strings represent the exact same date and time. And don't forget that sorting these strings (in these formats) in alphabetical order puts them in chronological order, which means there is no need to store them as date objects in the database since you can sort and query chronologically using a basic a-to-z sort.

提交回复
热议问题