Swift - Get local date and time Swift - Get local date and time ios ios

Swift - Get local date and time

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()

Leo's answer great. I just wanted to add a way to use it as a computed property.

 var currentTime: String {      Date().description(with: .current)  }

Use it like so:


Or you can encapsulate it:

extension String {     static var currentTime: String {         Date().description(with: .current)     }}

And then you can use it anywhere you use a string:

var time: String = .currentTime