Dani Kemper
Dani Kemper

Reputation: 343

If minutes are < 9 add a 0 before it

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

Answers (2)

Apix_D
Apix_D

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

rmaddy
rmaddy

Reputation: 318814

You have two choices.

  1. 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.
    
  2. 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

Related Questions