Search code examples
swiftnsdatensdateformatternscalendar

NSCalendarUnitDay shows the current day as a single digit int. How can I make it 2 digits such as "03"?


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"?


Solution

  • In ObjectiveC it will be

    NSString *strDate = [NSString stringWithFormat:@"%02d%02d", components.day, components.month];