In the following example we want to get the date of the specified day-of-the-year. We can define a calendar for a specific day of the year by setting the java.util.Calendar
object DAY_OF_YEAR
field using the set()
method. The method take the field to be set and a value.
package org.kodejava.util;
import java.util.Calendar;
public class DayOfYearToDate {
public static void main(String[] args) {
// In the example we want to get the date value of the specified
// day of the year. Using the calendar object we can define our
// calendar for a specific day of the year.
int dayOfYear = 112;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, dayOfYear);
System.out.println("Day " + dayOfYear + " of the current year = "
+ calendar.getTime());
// If you want to get the date for a specific day of year and for
// a specific year, you can also pass the year information to the
// calendar object.
int year = 2020;
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_YEAR, dayOfYear);
System.out.println("Day " + dayOfYear + " in year " + year
+ " = " + calendar.getTime());
}
}
And here is an example result of the code above:
Day 112 of the current year = Thu Apr 22 06:34:14 CST 2021
Day 112 in year 2020 = Tue Apr 21 06:34:14 CST 2020
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023
Thanks man.
You are welcome, Zack 🙂
2020 is a leap year so day 60 for it should be Feb 29. Not Mar 1.
Hi Shashi,
There was a bug in the code, need to add the following line in the code above after setting the calendar year to year 2020.