Reputation: 343
with this code you can save the current time but if the Minutes < 9 than it gives you the time in 5:9 instead of 5:09. How can you fix this?
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let Tijd = "\(hour) : \(minutes)"
Upvotes: 3
Views: 1568
Reputation: 1101
A solution for SwiftUi:
let date = Date()
Text(date, style: .time) // January 8, 2023
Text(date, style: .date) // 12:08 PM
Upvotes: 0
Reputation: 318814
You have two choices.
Use a String(format:)
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let tijd = String(format:"%d:%02d", hour, minutes) // change to "%02d:%02d" if you also want the hour to be 2-digits.
Use DateFormatter
.
let date = Date()
let df = DateFormatter()
df.dateFormat = "H:mm" // Use "HH:mm" if you also what the hour to be 2-digits
let tijd = df.string(from: date)
Upvotes: 11