iOS从一年中的日期获取日期 [英] iOS Get Date from Day of Year

查看:86
本文介绍了iOS从一年中的日期获取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于stackoverflow的常见问题是如何从日期获取年份,但是如何从日期获取日期?

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;

推荐答案

假设您知道想要的年份和日期的实际时间无关紧要,并且您设置了正确的语言环境和时区,则只需将一年中的日期和年份从组件转换回日期.同样,您可能需要确定应用程序需要处理的时间部分,并且必须确保日历实际上适用于日期和年份,但是要假设您在示例中列出的公历和第200天2013年(2013年7月19日),您可能会这样:

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

如果我要执行此操作,由于我的当前语言环境位于America/Los_Angeles所在的时区,并且我没有配置日历,因此我会得到一个2013年7月19日@ 07:00的日期.

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.

这篇关于iOS从一年中的日期获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆