Instantly share code, notes, and snippets.

What would you like to do?
Swift 3: Working with dates
//: # Swift 3: Working with dates
import Foundation
let date = Date()
let myLocale = Locale(identifier: "bg_BG")
//: ### Setting an application-wide `TimeZone`
//: Notice how we use if-let in case the abbreviation is wrong. It will fallback to the default timezone in that case.
if let myTimezone = TimeZone(abbreviation: "EEST") {
//: ### Using a `DateFormatter`
//: You can set a locale and styles to the date formatter. This allows the dates to be formatted in the given language and provides automatic handling of the preferred date formatting in the locale
let formatter = DateFormatter()
formatter.locale = myLocale
formatter.dateStyle = .medium
formatter.timeStyle = .medium
var dateStr = formatter.string(from: date)
print("1. \(dateStr)")
var calendar = Calendar(identifier: .gregorian)
calendar.locale = myLocale
//: ### Fetching `DateComponents` off a `Date`
//: Notice how *a locale is needed for the month symbols to be reported correctly*
let dateComponents = calendar.dateComponents([.day, .month, .year], from: date)
let monthName = calendar.monthSymbols[dateComponents.month! - 1]
print ("2. \(!) \(monthName) \(dateComponents.year!)")
//: #### Constructing a `Date` object from a `DateComponents` object
//: You need a `DateComponents` object and a `Calendar` object instances to do so
if let componentsBasedDate = dateComponents) {
let componentsBasedDateStr = formatter.string(from: componentsBasedDate)
print("3. \(componentsBasedDateStr)")

This comment has been minimized.

cschep commented Oct 21, 2016

very helpful, thank you!


This comment has been minimized.

SketchySwift commented Nov 13, 2016

Thanks a lot! How can I split the date so that it can be used for 4 labels. I want it to be like this:


so there would be 4 different labels on the screen! Thanks


This comment has been minimized.

AnselBaikal commented Dec 12, 2016

I already add "import Foundation" to my code. But when I use let date = Date(), there is an error:Use of unresolved identifier 'Date'


This comment has been minimized.

Pratik-Somaiya commented Mar 6, 2017

Very Helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment