如何以客观c

时间:2018-04-10 08:12:27

标签: ios objective-c nsdatecomponentsformatter

您好亲爱的我想要检索一年中的天数,例如今天是4月10日,我知道它是该月的第10天,但如果我想要像今天这样的一年中的第一天是第99天年。

这是我到目前为止所做的:

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

打印:当月10日

我想要的:一年中第99天当天的耳数。

答案:How do you calculate the day of the year for a specific date in Objective-C?

2 个答案:

答案 0 :(得分:1)

根据Unicode Technical Standard #35,一年中的某一天用D(1..3位数)表示。请记住使用3位数,因为年份可以有365天

[yearlyDay setDateFormat:@"DDD-yyyy"];

输出:

  

@ “100-2018”

如果要将其存储为整数,请尝试

NSDate *currentDate = [NSDate date];
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:@"DDD"];
NSString *string = [formatter stringFromDate:currentDate];
NSInteger dayOfYear = [string integerValue];

答案 1 :(得分:0)

使用它。

//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);

或者这个。

NSCalendar *gregorian =
    [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSUInteger dayOfYear =
    [gregorian ordinalityOfUnit:NSCalendarUnitDay
                         inUnit:NSCalendarUnitYear forDate:[NSDate date]];

    NSLog(@"%d", dayOfYear);