3

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)"
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Dani Kemper
  • 343
  • 2
  • 10
  • 1
    Use a date formatter with an appropriately configured date format. Don't write this date to string conversion yourself. Most people don't right dates/times as you do. You can't forget about internationalization. – Alexander Sep 18 '17 at 15:41
  • 2
    Possible duplicate of [Swift number formatting](https://stackoverflow.com/questions/26167453/swift-number-formatting) – Davy M Sep 18 '17 at 15:42
  • 1
    The question I cited shows how to get strings in general to print out with leading zeroes or taking up a certain amount of space. – Davy M Sep 18 '17 at 15:42

2 Answers2

11

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)
    
rmaddy
  • 314,917
  • 42
  • 532
  • 579
0

A solution for SwiftUi:

let date = Date()

Text(date, style: .time) // January 8, 2023
Text(date, style: .date) // 12:08 PM
Iskandir
  • 937
  • 1
  • 9
  • 21