Thursday, September 6, 2007

Java Code For Comparing Dates

Calendar xmas = new GregorianCalendar(1998, Calendar.DECEMBER, 25);

Calendar newyears = new GregorianCalendar(1999, Calendar.JANUARY, 1);

// Determine which is earlier
boolean b = xmas.after(newyears); // false
b = xmas.before(newyears); // true


// Get difference in milliseconds
long diffMillis = newyears.getTimeInMillis()-xmas.getTimeInMillis();

// Get difference in seconds
long diffSecs = diffMillis/(1000); // 604800

// Get difference in minutes
long diffMins = diffMillis/(60*1000); // 10080

// Get difference in hours
long diffHours = diffMillis/(60*60*1000); // 168

// Get difference in days
long diffDays = diffMillis/(24*60*60*1000); // 7

Saturday, September 1, 2007

Java Code For Getting the Current Date : java.util.Date

Calendar cal = new GregorianCalendar();

// Get the components of the date
int era = cal.get(Calendar.ERA); // 0=BC, 1=AD
int year = cal.get(Calendar.YEAR); // 2002
int month = cal.get(Calendar.MONTH); // 0=Jan, 1=Feb, ...
int day = cal.get(Calendar.DAY_OF_MONTH); // 1...
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 1=Sunday, 2=Monday, ...

Java Code For Creating a Date Object for a Particular Date

Calendar xmas = new GregorianCalendar(1998, Calendar.DECEMBER, 25);
Date date = xmas.getTime();

Java Code to Determine If a Year Is a Leap Year : java.util.Date

GregorianCalendar cal = new GregorianCalendar();
boolean b = cal.isLeapYear(1998); // false
b = cal.isLeapYear(2000); // true
b = cal.isLeapYear(0); // true