Number of day of current year in iOS

后端 未结 4 522
清歌不尽
清歌不尽 2021-01-16 18:30

I want to find number of day today is in current year. e.g, if today is Mar15, 2012 I should get 75(31 + 29 + 15). Or we can simply say that number of days between today and

4条回答
  •  花落未央
    2021-01-16 18:48

    According to the data format reference, you can use the D specifier to represent the day of the year. A date formatter isn't so helpful if you want to perform some calculations, but if you just want to display the day of year it's probably the easiest way to go. The code would look something like:

    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    
    [df setCalendar:cal];
    [df setDateFormat:@"DDD"];    // D specifier used for day of year
    NSString *dayOfYearString = [df stringFromDate:someDate];  // you choose 'someDate'
    
    NSLog(@"The day is: %@", dayOfYearString);
    

提交回复
热议问题