How to get NSDate day, month and year in integer format?

前端 未结 9 1060
长情又很酷
长情又很酷 2020-12-07 15:31

I want to get the day, month and year components of NSDate in integer form i.e. if the date is 1/2/1988 then I should get 1, 2 and 1988 separately as an integer

相关标签:
9条回答
  • 2020-12-07 16:07

    Here you are,

    NSDate *currentDate = [NSDate date];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate]; // Get necessary date components
    
     [components month]; //gives you month
     [components day]; //gives you day
     [components year]; // gives you year
    

    You can use NSDateComponents for that as above.

    Please visit this page for details.

    Hope it helps.

    0 讨论(0)
  • 2020-12-07 16:07

    Put it in an extension and live your life

    0 讨论(0)
  • 2020-12-07 16:13

    Swift

    let components = NSCalendar.currentCalendar().components([.Day, .Month, .Year], fromDate: self)
    let day = components.day
    let month = components.month
    let year = components.year
    

    For convenience you can put this in an NSDate extension and make it return a tuple:

    extension NSDate: Comparable {
    
        var dayMonthYear: (Int, Int, Int) {
            let components = NSCalendar.currentCalendar().components([.Day, .Month, .Year], fromDate: self)
            return (components.day, components.month, components.year)
        }
    }
    

    Now you have to write only:

    let (day, month, year) = date.dayMonthYear
    

    If you wanted to e.g. get only the the year you can write:

    let (_, _, year) = date.dayMonthYear
    
    0 讨论(0)
提交回复
热议问题