Swift - Get local date and time

前端 未结 10 688
挽巷
挽巷 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:33

    update: Xcode 8.2.1 • Swift 3.0.2

    You can also use the Date method description(with locale: Locale?) to get user's localized time description:

    A string representation of the Date, using the given locale, or if the locale argument is nil, in the international format YYYY-MM-DD HH:MM:SS ±HHMM, where ±HHMM represents the time zone offset in hours and minutes from UTC (for example, “2001-03-24 10:45:32 +0600”).

    description(with locale: Locale?)

    Date().description(with: .current)   // "Monday, February 9, 2015 at 05:47:51 Brasilia Summer Time"
    

    The method above it is not meant to use when displaying date and time to the user. It is for debugging purposes only.

    When displaying local date and time (current timezone) to the user you should respect the users locale and device settings. The only thing you can control is the date and time style (short, medium, long or full). Fore more info on that you can check this post shortDateTime.

    If your intent is to create a time stamp UTC for encoding purposes (iso8601) you can check this post iso8601

提交回复
热议问题