0

I got days in year in format 1-366

How do I convert them to actuall date like 12.12. etc.? + how it's with the 29.2.?

Thanks for answer!

Tomáš John
  • 314
  • 4
  • 14
  • 1
    You cannot do it without exact year, because of leap years. – mkrakhin May 06 '15 at 09:47
  • So when I pick some year, I can set him to Calendar, then multiply number_of_days *24*60*60*1000 getting miliseconds and add it to calendar and get actual date? – Tomáš John May 06 '15 at 09:52

2 Answers2

4

Seems easy to do with Calendar:

final Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, 366);
final Date date = new Date(calendar.getTimeInMillis());

And if you want to offset a year for example:

calendar.add(Calendar.YEAR, 1);
shkschneider
  • 17,833
  • 13
  • 59
  • 112
  • 2
    Be careful that this Calendar will contain its creation time - you may want to truncate the H/M/S fields to get rid of these. – hugh May 06 '15 at 09:57
  • Good point. Using `set()` for hours, minutes and seconds to `0` should do, right? – shkschneider May 06 '15 at 09:59
  • Yep, but I think there's a millisecond field too. If you've got Apache commons-lang to hand, its DateUtils has a handy truncate method to do this. – hugh May 06 '15 at 10:33
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html) and [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html) are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. The `Year` and `LocalDate` classes in java.time handle this chore nicely. – Basil Bourque Feb 17 '17 at 23:03
1

You can use joda-time-android:

MutableDateTime mutableDateTime = new MutableDateTime();
mutableDateTime.setYear(2012);
mutableDateTime.setDayOfYear(366);
Ivan Mamontov
  • 2,874
  • 1
  • 19
  • 30
otedikova
  • 21
  • 5