2

So I'm creating a date string in MMyy format:

        var components: NSDateComponents!
        components = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: NSDate()) as NSDateComponents
        let stringDate = "\(components.month)\(components.day)" // "113"

If a day is less than 10 then I get a 3 digit number as a string.

How do I change things so that I get a 4 digit number as a string instead e.g. "1103"?

l0gg3r
  • 8,864
  • 3
  • 26
  • 46
LondonGuy
  • 10,778
  • 11
  • 79
  • 151
  • I would have never typed in "leading zeros for int in swift" to be honest. But the answer below sorted things out. – LondonGuy Nov 03 '14 at 12:12
  • "Leading zeros" is a common term for what you wanted. A complete description of the print formats can be found here: http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html. – Alternatively, you could use a NSDateFormatter in your case. – Martin R Nov 03 '14 at 12:20
  • Thanks. I will make note of this. – LondonGuy Nov 03 '14 at 15:02

1 Answers1

3

In ObjectiveC it will be

NSString *strDate = [NSString stringWithFormat:@"%02d%02d", components.day, components.month];
l0gg3r
  • 8,864
  • 3
  • 26
  • 46