Reputation: 1032
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 ?
Upvotes: 44
Views: 31782
Reputation: 547
you can get by following code in objective c
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
int year = [components year];
NSString *strFromyear = [NSString stringWithFormat:@"%d",year];
Upvotes: 2
Reputation: 10009
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.
Upvotes: 121
Reputation: 79726
Swift
Easier way to get any elements of date as an optional String.
extension Date {
// Year
var currentYear: String? {
return getDateComponent(dateFormat: "yy")
//return getDateComponent(dateFormat: "yyyy")
}
func getDateComponent(dateFormat: String) -> String? {
let format = DateFormatter()
format.dateFormat = dateFormat
return format.string(from: self)
}
}
print("-- \(Date().currentYear)") // result -- Optional("2017")
Upvotes: 0
Reputation: 17535
In Swift you can get only year by given code
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy"
let dateStr = formatter.stringFromDate(NSDate())
print(dateStr)
Output:
2017
Upvotes: 3
Reputation: 389
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.
Upvotes: 38