iphone Get current year as string

后端 未结 5 1182
迷失自我
迷失自我 2021-02-01 01:33

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 ye

相关标签:
5条回答
  • 2021-02-01 02:29

    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];
    
    0 讨论(0)
  • 2021-02-01 02:30
    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.

    0 讨论(0)
  • 2021-02-01 02:30

    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 讨论(0)
  • 2021-02-01 02:32
    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.

    0 讨论(0)
  • 2021-02-01 02:37

    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

    0 讨论(0)
提交回复
热议问题