How can I get local date and time in Swift?
let last_login = String(NSDate.date())
A timestamp is that which contain some characters that are in an encoded form which will contain any event, date or time etc. For more information, you can also go through from here.
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
In case you want to get a Date object and not a string representation you can use the following snippet:
extension Date { func localDate() -> Date { let nowUTC = Date() let timeZoneOffset = Double(TimeZone.current.secondsFromGMT(for: nowUTC)) guard let localDate = Calendar.current.date(byAdding: .second, value: Int(timeZoneOffset), to: nowUTC) else {return Date()} return localDate } }
Use it like this:
let now = Date().localDate()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With