Share on Google+Share on Google+

Implement Date Class

Advertisement
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));
	}
}

Advertisements

Advertisement

Posted on: July 12, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.