Search code examples
javajulian-date

Julian day of the year in Java


I have seen the "solution" at http://www.rgagnon.com/javadetails/java-0506.html, but it doesn't work correctly. E.g. yesterday (June 8) should have been 159, but it said it was 245.

So, does someone have a solution in Java for getting the current date's three digit Julian day (not Julian date - I need the day this year)?

Thanks! Mark


Solution

  • If all you want is the day-of-year, why don'you just use GregorianCalendars DAY_OF_YEAR field?

    import java.util.GregorianCalendar;
    public class CalTest {
        public static void main(String[] argv) {
            GregorianCalendar gc = new GregorianCalendar();
            gc.set(GregorianCalendar.DAY_OF_MONTH, 8);
            gc.set(GregorianCalendar.MONTH, GregorianCalendar.JUNE);
            gc.set(GregorianCalendar.YEAR, 2010);
            System.out.println(gc.get(GregorianCalendar.DAY_OF_YEAR));
    }
    

    }

    Alternatively, you could calculate the difference between today's Julian date and that of Jan 1st of this year. But be sure to add 1 to the result, since Jan 1st is not the zeroth day of the year:

    int[] now = {2010, 6, 8};
    int[] janFirst = {2010, 1, 1};
    double dayOfYear = toJulian(now) - toJulian(janFirst) + 1
    System.out.println(Double.valueOf(dayOfYear).intValue());