001package jmri.util; 002 003import java.util.Calendar; 004import java.util.GregorianCalendar; 005 006/** 007 * Common utility methods for working with Calendar and Date objects. 008 * 009 * @author Paul Bender Copyright 2014 010 */ 011public class DateUtil { 012 013 // return a GregorianCalendar representation of the given julian date 014 // for reference, see: 015 // http://aa.usno.navy.mil/faq/docs/JD_Formula.php 016 // @param long julianDay number of days since January 1,4713BC. 017 // @return {@link java.util.GregorianCalendar} representation of julianDay 018 static public GregorianCalendar calFromJulianDate(long julianDay) { 019 long L = julianDay + 68569; 020 long N = 4 * L / 146097; 021 L = L - (146097 * N + 3) / 4; 022 long year = 4000 * (L + 1) / 1461001; 023 L = L - 1461 * year / 4 + 31; 024 long month = 80 * L / 2447; 025 long day = L - 2447 * (month) / 80 - 31; 026 L = month / 11; 027 month = month + 2 - 12 * L; 028 year = 100 * (N - 49) + year + L; 029 GregorianCalendar returnCal = new GregorianCalendar((int) year, (int) month, (int) day, 0, 0); 030 031 return (returnCal); 032 } 033 034 // return a julian date representation of the given GregorianCalendar date 035 // for reference, see: 036 // http://aa.usno.navy.mil/faq/docs/JD_Formula.php 037 // @param {@link java.util.GregorianCalendar} cal i 038 // @return julianDate representation of the date represented by cal. 039 static public long julianDayFromCalendar(java.util.GregorianCalendar cal) { 040 int I = cal.get(Calendar.YEAR); 041 int J = cal.get(Calendar.MONTH) + 1; // GregorianCalendar starts month 042 // at 0. Calculation requres month 043 // starting at 1. 044 045 int K = cal.get(Calendar.DAY_OF_MONTH); 046 047 long day = K - 32075 + 1461 * (I + 4800 + (J - 14) / 12) / 4 + 367 * (J - 2 - (J - 14) / 12 * 12) / 12 - 3 * ((I + 4900 + (J - 14) / 12) / 100) / 4; 048 049 return day; 050 } 051 052}