java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to convert day of the year to date?

package com.javacoderanch.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 of year " + dayOfYear + " = "
		+ 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 = 2004;
	calendar.set(Calendar.YEAR, year);
	System.out.println("Day of year " + dayOfYear + " in year " + year
		+ " = " + calendar.getTime());
    }
}

And here is an example result of the code above:

Day of year 112 = Sun Apr 22 16:53:03 GMT+07:00 2007
Day of year 112 in year 2004 = Wed Apr 21 16:53:03 GMT+07:00 2004