Get current date in Swift 3?

SwiftNsdate

Swift Problem Overview


How can I set label.text current date in Swift 3?

I want to print just today to the screen. I did not find how to do that.

In c# is very simple:

var date = DateTime.Now

I need to write 15.09.2016 in swift 3. thanks

Swift Solutions


Solution 1 - Swift

You say in a comment you want to get "15.09.2016".

For this, use Date and DateFormatter:

let date = Date()
let formatter = DateFormatter()

Give the format you want to the formatter:

formatter.dateFormat = "dd.MM.yyyy"

Get the result string:

let result = formatter.string(from: date)

Set your label:

label.text = result

Result:

> 15.09.2016

Solution 2 - Swift

You can do it in this way with Swift 3.0:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year =  components.year
let month = components.month
let day = components.day

print(year)
print(month)
print(day)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyucelView Question on Stackoverflow
Solution 1 - SwiftEric AyaView Answer on Stackoverflow
Solution 2 - SwiftJorge CasariegoView Answer on Stackoverflow