Reputation: 321
Hello dear I want to retrieve the number of day in the year e.g today is 10th April and I know its 10th day of the month but what if I want the number of the day of the year like today is 99th day of the year.
This is what I have done so far:
NSInteger todaydaysyear;
NSDateFormatter *yearlyDay = [[NSDateFormatter alloc] init];
[yearlyDay setDateFormat:@"dd-yyyy"];
NSDate *currentdateyear = [NSDate date];
NSString *cureentdatestryear = [yearlyDay stringFromDate:currentdateyear];
NSDate *startDateyear = [yearlyDay dateFromString:cureentdatestryear];
NSDateComponents *componentsyear = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitYear fromDate:startDateyear];
todaydaysyear = [componentsyear day];
NSLog(@"here is the day of the year e.g 99th day but not prints month day why%ld", (long)todaydaysyear);
Prints: 10 the current day of the month
What I want: 99th day of the year the current day of the ear count.
Ans: How do you calculate the day of the year for a specific date in Objective-C?
Upvotes: 0
Views: 795
Reputation: 1334
Use this.
//Assuming your calendar is initiated like this
NSCalendar *_calendar = [NSCalendar currentCalendar];
NSInteger yearlyDay;
//Fetch the weekOfYear number
NSInteger weekOfYear = [_calendar component:NSCalendarUnitWeekOfYear fromDate:[NSDate date]];
weekOfYear--;
//Fetch the weekDay number
NSInteger weekDay = [_calendar component:NSCalendarUnitWeekday fromDate:[NSDate date]];
yearlyDay = weekOfYear*7 + weekDay;
NSLog(@"%d", yearlyDay);
or this.
NSCalendar *gregorian =
[[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSUInteger dayOfYear =
[gregorian ordinalityOfUnit:NSCalendarUnitDay
inUnit:NSCalendarUnitYear forDate:[NSDate date]];
NSLog(@"%d", dayOfYear);
Upvotes: 0
Reputation: 6982
According to Unicode Technical Standard #35, the day of year is denoted by D
(1..3 digits). Remember to use 3 digits, because year can have 365 days
[yearlyDay setDateFormat:@"DDD-yyyy"];
Output:
@"100-2018"
If you want to store it as integer, try
NSDate *currentDate = [NSDate date];
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:@"DDD"];
NSString *string = [formatter stringFromDate:currentDate];
NSInteger dayOfYear = [string integerValue];
Upvotes: 1