Home Tutorial Java Core Implement Date Class

 
 

Implement Date Class
Posted on: July 12, 2010 at 12:00 AM
Here we are going to implement Date Class.

Implement Date Class

The class Date represents a specific instant in time. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Here we are going to implement Date Class.

Here is the 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(7, 12, 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));
	}
}

Related Tags for Implement Date Class:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.