w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to model date at different precision as either year or month/year or day/month/year in Cocoa?

An NSDate will always have the year, month, day and time. You can use the code below to return a date with the specified values:

- (NSDate *)dateWithYear:(NSInteger)year Month:(NSInteger)month
Day:(NSInteger)day {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.year = year;
    components.month = month;
    components.day = day;
    return [calendar dateFromComponents:components];

If you want to change the display of the date, you can use NSDateFormatter:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy"]; // shows only year
[dateFormatter setDateFormat:@"MMM yyyy"]; //shows month & year

To convert the date into a string using the formatter use:

NSString *dateString = [formatter stringFromDate:date];

read more on Date Formatting here: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.