iOS Get Date from Day of Year

六眼飞鱼酱① 提交于 2019-12-20 02:53:21

问题


The common question on stackoverflow is how to get the Day of Year from a date but how to you get the date from the Day of Year?

I'm using the following code to generate the Day of Year but how to I do the converse?

// Calculate Day of the Year
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
    setDayOfYear = dayOfYear;
    return setDayOfYear;

回答1:


Assuming you know the year you want and the actual time of the date doesn't matter and you have the correct locale and time zones set up, you can just convert the day of the year and year from components back into a date. Again, you may need to decide what your application needs to do about the time component and you have to make sure that the day and year actually make sense for the calendar, but assuming the gregorian calendar you listed in your example, and the 200th day of 2013 (19 July, 2013), you could so something like this:

NSDateComponents* components = [[NSDateComponents alloc] init];
[components setDay:200];
[components setYear:2013];
NSDate* july19_2013 = [gregorian dateFromComponents:components];

If I were to run this, I'd get a date that's 19 July, 2013 @ 07:00 since my current locale is in a time zone equiv of America/Los_Angeles and I didn't configure the calendar.



来源:https://stackoverflow.com/questions/17564230/ios-get-date-from-day-of-year

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!