开发者

iphone Get current year as string

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

Also开发者_如何学Python 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 NSStrings 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.


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


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];


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")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜