Home > Enterprise >  Showing the current time in seconds with a "0"
Showing the current time in seconds with a "0"

Time:11-02

I want to show the current time in seconds. However, I am using the DateFormatter for it. But I dont know how to show a 0 before the number, when it is under 10.

For example: I dont want 2, but 02.

This is my code so far:

let formatter = DateFormatter()
    formatter.dateFormat = "ss"
    
let time = formatter.string(from: date)

I also tried appending the 0, unfortunately it didnt work:

let timeWithNull1 = "0"   time
let timeWithNull2 = "0".appending(time)

CodePudding user response:

you can implement this, using String Interpolation

    let time = 5

let timeWithNull1 = time < 10 ? "0\(time)" : "\(time)";
print(timeWithNull1);

CodePudding user response:

My issue was that I was converting my String into a Int in another view. But since Ints dont allow these kinds of numbers it got converted to the number without the 0. Thank you for the suggestion with the String Interpolation, it is much shorter.

CodePudding user response:

The following code should do it on a DateFormatter object: dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

Full working example (tested with Xcode 14.01/macOS 13):

func getDateAsString(_ date: Date) -> String{
    ///Creates a DateFormatter object that will format the date
    let formatter = DateFormatter()
        ///Sets the date formatter to output the correct format.
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    ///Returns the string the formatter generates from the given date
    return formatter.string(from: date)
}
//Example usage
print(getDateAsString(Date()))
//Prints: 2022-11-01 11:27:39

Refer to the following StackOverflow question for more information: Swift - How can I get the current time in seconds?

  • Related