Anvil
Anvil

Reputation: 1865

Display date and time

In my app I get the date and time like this:

let date = Date()
        let calendar = Calendar.current
        let hour = calendar.component(.hour, from: date)
        let minute = calendar.component(.minute, from: date)
        let second = calendar.component(.second, from: date)
        let year = calendar.component(.year, from: date)
        let month = calendar.component(.month, from: date)
        let day = calendar.component(.day, from: date)   

And display the date and time like so:

let dateAndTime = ("\(day)-\(month)-\(year) at: \(hour):\(minute):\(second)")    

This works fine, but if the minute and second are <10 I would like it to show a 0 in front of the minute and second like this:
11-8-2019 at: 21:06:03
How can I do this

Upvotes: 1

Views: 92

Answers (1)

PGDev
PGDev

Reputation: 24341

Try using DateFormatter to get the required date format.

1. Using dateFormat, i.e.

let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd-MMM-yyy hh:mm:ss a"
print(formatter.string(from: date)) //13-Aug-2019 11:15:47 AM

2. Using dateStyle and timeStyle, i.e.

let date = Date()
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .medium
print(formatter.string(from: date)) //Aug 13, 2019 at 11:15:16 AM

Upvotes: 1

Related Questions