Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone Get current year as string

Tags:

objective-c

How do I get current year as string in Obj-C ?

Also how do I compare the same using another year value ?

Is it advisable to do a string comparision OR dirctly year-to-year comparision ?

like image 761
hmthur Avatar asked Jan 14 '11 09:01

hmthur


2 Answers

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];
NSString *yearString = [formatter stringFromDate:[NSDate date]];

// Swift
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy"
let year = dateFormatter.string(from: Date())

You can compare NSStrings via the -isEqualToString: method.

like image 75
Björn Marschollek Avatar answered Nov 17 '22 10:11

Björn Marschollek


NSCalendar *gregorian = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
NSInteger year = [gregorian component:NSCalendarUnitYear fromDate:NSDate.date];

Note: there are several calendar identifiers besides NSGregorianCalendar. Use whatever is appropriate for your locale. You can ask for whatever set of components you'd like by bitwise OR'ing the fields together (e.g., NSYearCalendarUnit | NSMonthCalendarUnit) and using components:fromDate instead. You can read about it in the Date and Time Programming Guide.

With calendar components as primitive types, comparisons are efficient.

like image 38
Steve Liddle Avatar answered Nov 17 '22 11:11

Steve Liddle