128

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

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
yucel
  • 1,311
  • 2
  • 9
  • 9

2 Answers2

315

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

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • 2
    In Swift 4.2, DateFormatter has both .dateStyle and .timeStyle properties. Instead of the somewhat opaque syntax above (which gives more fine-grained control - see https://nsdateformatter.com) you can use dateStyle combined with locale. – green_knight Jan 31 '19 at 18:48
72

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)
Dmitry
  • 14,306
  • 23
  • 105
  • 189
Jorge Casariego
  • 21,948
  • 6
  • 90
  • 97
  • 27
    I cannot believe even after Swift 3 that date handling is so bad! It's shameful considering Date in .NET was in version 1 in 2002 from memory. DateTime.Now or DateTime.Now.Month are so much easier! – csmith Apr 24 '17 at 01:07
  • 1
    How do you know if that day is a Mon, Tue, or Wed? – Joseph Astrahan Jun 25 '17 at 19:39
  • 1
    Check out SwiftDate Cocoapod if you'd like a much easier way to interact with dates in swift. – Rob Norback Jul 07 '17 at 21:26
  • 1
    @csmith That's because its still the old NSDate but with Swift syntax. It hasn't been rewritten. You're right though, it is a bit of a pain to work with. – bandejapaisa Aug 15 '17 at 09:45