Last active
August 29, 2015 14:02
-
-
Save cikasfm/4db36c50235df965762a to your computer and use it in GitHub Desktop.
MoonPhaseCalc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Moon Phase Calculator | |
* | |
* @author Zilvinas Vilutis | |
*/ | |
public class MoonPhaseCalc { | |
public final static String format = "yyyy-MM-dd"; | |
private static final int moonPhaseHours = 709; | |
private final Date start; | |
public MoonPhaseCalc() throws ParseException { | |
this( null ); | |
} | |
public MoonPhaseCalc( Date start ) throws ParseException { | |
if ( start != null ) { | |
this.start = start; | |
} | |
else { | |
this.start = new SimpleDateFormat( format ).parse( "2014-06-13" ); | |
} | |
} | |
/** | |
* Finds the next full moon phase date matching the given day of month and | |
* day of week. Used to find the next Friday, 13th with Full Moon :) | |
* | |
* @param dayOfMonth Day Of Month to match ( e.g. 13 ) - see {@link Calendar#DAY_OF_MONTH} | |
* @param dayOfWeek Day of Week to match ( 6 for Friday ) - see {@link Calendar#DAY_OF_WEEK} | |
* @return | |
*/ | |
public Date getNextFullMoon( int dayOfMonth, int dayOfWeek ) { | |
final Calendar cal = Calendar.getInstance(); | |
// validate input | |
if ( cal.getMinimum( Calendar.DAY_OF_MONTH ) > dayOfMonth || cal.getMaximum( Calendar.DAY_OF_MONTH ) < dayOfMonth ) { | |
throw new IllegalArgumentException( "Invalid day of month provided!" ); | |
} | |
if ( cal.getMinimum( Calendar.DAY_OF_WEEK ) > dayOfWeek || cal.getMaximum( Calendar.DAY_OF_WEEK ) < dayOfWeek ) { | |
throw new IllegalArgumentException( "Invalid day of week provided!" ); | |
} | |
cal.setTime( start ); | |
while ( true ) { | |
cal.add( Calendar.HOUR, moonPhaseHours ); | |
if ( cal.get( Calendar.DAY_OF_MONTH ) == dayOfMonth && cal.get( Calendar.DAY_OF_WEEK ) == dayOfWeek ) { | |
return cal.getTime(); | |
} | |
} | |
} | |
public static void main( String[] args ) throws ParseException { | |
final MoonPhaseCalc moonPhaseCalc = new MoonPhaseCalc(); | |
final Date nextFullMoon = moonPhaseCalc.getNextFullMoon( 13, Calendar.FRIDAY ); | |
final String nexFullMoonOnFriday = new SimpleDateFormat( format ).format( nextFullMoon ); | |
System.out.println( nexFullMoonOnFriday ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment