Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


deepeka
javaprograms
1 Answer(s)      4 years and 3 months ago
Posted in : Java Beginners


develop date class in java similar to one avilable in java.util package use javadoc comments

Advertisement
View Answers

August 14, 2010 at 10:53 AM


Hi Friend,

Try the following code:

public class Date {

private final int month;
private final int day;
private final int year;

public Date(int m, int d, int y) {
if (!isValid(m, d, y))
throw new RuntimeException("Invalid");
month = m;
day = d;
year = y;
}

private static boolean isValid(int m, int d, int y) {
int[] DAYS = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (m < 1 || m > 12)
return false;
if (d < 1 || d > DAYS[m])
return false;
if (m == 2 && d == 29 && !isLeapYear(y))
return false;
return true;
}

private static boolean isLeapYear(int y) {
if (y % 400 == 0)
return true;
if (y % 100 == 0)
return false;
return (y % 4 == 0);
}

public Date next() {
if (isValid(month, day + 1, year))
return new Date(month, day + 1, year);
else if (isValid(month + 1, 1, year))
return new Date(month + 1, 1, year);
else
return new Date(1, 1, year + 1);
}

public boolean isAfter(Date b) {
return compareTo(b) > 0;
}

public boolean isBefore(Date b) {
return compareTo(b) < 0;
}

public int compareTo(Date b) {
if (year != b.year)
return year - b.year;
if (month != b.month)
return month - b.month;
return day - b.day;
}

public String toString() {
return day + "-" + month + "-" + year;
}

public static void main(String[] args) {
Date today = new Date(9, 30, 2010);
System.out.println(today);
Date nextDate = today.next();
System.out.println(nextDate);
System.out.println(today.isAfter(nextDate));
System.out.println(today.next().isAfter(today));
System.out.println(today.isBefore(nextDate));
System.out.println(nextDate.compareTo(today));
}
}

Thanks


Related Tutorials/Questions & Answers:
Advertisements
 

 

 

DMCA.com