Skip to content

Instantly share code, notes, and snippets.

@Justin42
Forked from crzye8s/Date2.java
Created September 5, 2012 20:36
Show Gist options
  • Select an option

  • Save Justin42/3644330 to your computer and use it in GitHub Desktop.

Select an option

Save Justin42/3644330 to your computer and use it in GitHub Desktop.
// Lab 01 - Ex 03.15 - Date2
// CIS 282
// Jonathan Lee
public class Date2
{
private int year;
private int month;
private int day;
public Date2( int theYear ) {
month = 1;
day = 1;
year = checkYear( theYear );
}
public Date2( int theMonth, int theYear ) {
month = checkMonth ( theMonth );
day = 1;
year = checkYear ( theYear );
}
public Date2( int theMonth, int theDay, int theYear )
{
month = checkMonth ( theMonth );
month = checkDay ( theDay );
month = checkYear ( theYear );
}
public Date2( Date2 date)
{
this( date.getMonth(), date.getDay(), date.getYear() );
}
public void setMonth( int m )
{
month = checkMonth( m );
}
public void setDay( int d)
{
day = checkDay ( d );
}
public void setYear( int y)
{
day = checkYear ( y );
}
public int getMonth()
{
return month;
}
public int getDay()
{
return day;
}
public int getYear()
{
return year;
}
private int checkMonth( int testMonth )
{
if ( testMonth > 0 && testMonth <= 12 )
return testMonth;
else
{
System.out.println( "Month must be from 1 to 12. Set to 1." );
return 1;
}
}
private int checkDay( int testDay )
{
int daysinMonth[] =
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if ( testDay > 0 && testDay <= daysinMonth[ month ] )
return testDay;
if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||
( year % 4 == 0 && year % 100 != 0 ) ) )
return testDay;
System.out.println( "Day is invalid. Set to 1." );
return 1;
}
private int checkYear( int testYear )
{
if ( testYear > 1752 )
return testYear;
else
{
System.out.println( "Year must be greater than 1752. Set to 1900." );
return 1900;
}
}
public String toString()
{
return String.format(
"%d/%d/%d", getMonth(), getDay(), getYear() );
}
@Override
public boolean equals(Object object){
if ( object !instanceof Date2 ) return false;
Date2 date2 = (Date2)object;
if (month != date2.getMonth()) return false;
if (day != date2.getDay()) return false;
if (year != date2.getYear()) return false;
else return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment