How to get NSDate day, month and year in integer f

2019-01-16 07:01发布

问题:

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. How can I do this in iOS? I found the similar question but the method descriptionWithCalendarFormat: gives a warning and seems to be deprecated by now.

回答1:

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.



回答2:

Yes by the use of NSCalendar, though, i think this will make your work.

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger day = [components day];    
NSInteger month = [components month];
NSInteger year = [components year];


回答3:

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


回答4:

You can use NSDateComponents to get this,

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *currDate = [NSDate date];
NSDateComponents *dComp = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) 
                                      fromDate:currDate];

int day = [dComp day];
int month = [dComp month];
int year = [dComp year];


回答5:

To those who just copy and paste directly from the web, like me, this is a small update for iOS 8

NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
[components day]; //Day
[components month];//Month
[components year];//Year

The difference is NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit have been deprecated



回答6:

Put it in an extension and live your life