0

Is there a straight way to get a date component with 'n' number of characters?

(I'm a beginner in swift)

Context/What I want to achieve:

I want to get a String with the same amount of characters of a date component.

For example:

Seconds: Always with 2 digits (01, 02, 03... 58, 59)

Nanoseconds: Always with 9 digits (000000001, 000000056... 526895648)


What have I done so far?:

I created a method that adds a certain amount of "0" depending on how long I want the length to be.

func addZeros (forNumber number: Int, desiredLenght: Int) -> String {
    var numberToEvaluate = "\(number)"
    if numberToEvaluate.count < desiredLenght {
        let difference = desiredLenght - numberToEvaluate.count
        let fillWith = String(repeating: "0", count: difference)
        numberToEvaluate = "\(fillWith)\(numberToEvaluate)"
    }
    return numberToEvaluate
}

let second = calendar.component(.second, from: date)
let newSecond = addZeros(forNumber: second, desiredLenght: 2)
// So, if second returns '2', newSecond will be "02"

let nanosec = calendar.component(.nanosecond, from: date)
let newNanosec = addZeros(forNumber: nanosec, desiredLenght: 9)
// And if nanoSec returns '52', newSecond will be "000000052"

Since I will be using this a lot, is there a more elegant way to do this?

I have read about DateFormatter but still don't quite get if I can use it for this.

Suggestions to achieve what I want in other ways are welcome

Thank you :)

Ryoko
  • 75
  • 6
  • 1
    Use a date formatter, or this https://stackoverflow.com/questions/25566581/leading-zeros-for-int-in-swift – Martin R Jul 16 '18 at 04:46
  • The body of your `addZeros` method can be written in one line: `return String(format: "%0\(desiredLength)ld", number)` – vadian Jul 16 '18 at 05:01

0 Answers0