How do I convert day-of-the-year to date?

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.example.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);
        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 = Sat Apr 22 00:34:10 WITA 2017
Day 112 in year 2020 = Wed Apr 22 00:34:10 WITA 2020

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

2 Comments

Leave a Reply