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 ?
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 NSString
s via the -isEqualToString:
method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With