0

I'm looking for a way to display the current date in a label with Swift 3. Currently I'm using DateFormatter.dateFormat but the only output I get is

dd.MM.yyyy

Here is the line of code:

lbl_Date.text = DateFormatter.dateFormat(fromTemplate: "MMddyyyy", options: 0, locale: NSLocale(localeIdentifier: "de-AT") as Locale)

And my expected output for today should be:

11.12.2016

I know that I can get the time with the dateTimeComponents but I haven't figured out how I can get only the date (day, month and year) in my label:

// get the current date and time
    let currentDateTime = Date()

    // get the user's calendar
    let userCalendar = Calendar.current

    // choose which date and time components are needed
    let requestedComponents: Set<Calendar.Component> = [
        .year,
        .month,
        .day,
        .hour,
        .minute,
        .second
    ]

    // get the components
    let dateTimeComponents = userCalendar.dateComponents(requestedComponents, from: currentDateTime)

What is there the cleanest way to display the current date in my label?

vadian
  • 274,689
  • 30
  • 353
  • 361
Fabian
  • 541
  • 9
  • 30
  • 1
    That function is to create a date format. That for that is then used to render a date into a string. Look at any of these thousands of similar questions on stack overflow to find out how. – Fogmeister Dec 11 '16 at 10:26
  • Possible duplicate of [Convert NSDate to NSString](http://stackoverflow.com/questions/576265/convert-nsdate-to-nsstring) – Fogmeister Dec 11 '16 at 10:27

1 Answers1

5

Forget Calendar and DateComponents. Use DateFormatter

let currentDateTime = Date()
let formatter = DateFormatter()

If you want a fixed format set the dateFormat to

formatter.dateFormat = "dd.MM.yyyy"

alternatively if you want a format depending on the current locale set timeStyle and dateStyle rather than the format property

formatter.timeStyle = .none
formatter.dateStyle = .medium

Now get the string

let dateString = formatter.string(from: currentDateTime)
vadian
  • 274,689
  • 30
  • 353
  • 361