Wednesday, October 21, 2009

Date to calendar,date utils... a simple example

Sometimes in you application you will require the calendar logic. In java the Date class methods are mostly deprecated and usage of Calendar class is encouraged. This utility class will do the operations using the Calendar api. This also can be use as Date to calendar converter or calendar to date converter. The methods are synchronized, so are threadsafe. I didn't make the calendar static, you can do that is required.


import java.util.Calendar;
import java.util.Date;

/**
 * This class will operate as a calendar. First set a date.
 * Then change the day,month or year as require. 
 * Then get the date back. There is also a feature of getting the current date, if needed,
 * which you can set as the base date again and do operations. 
 * Only date operations are permitted. 
 * Add logic, if you want the time related operations too.
 */
public class CustomCalendar {

private Calendar date;
private static final int BASEYEAR = 1900;
//Set the date before operation. Converts date to calendar for easier operation
public CustomCalendar(Date date) {
 super();
  this.date = Calendar.getInstance();
  this.date.setTime(date);
}

public CustomCalendar(Calendar date) {
 super();
 this.date = date;
}

//sets the prev year relative to the date already set(In constructor).
public  synchronized void prevYear() {
 int year = date.get(Calendar.YEAR)-BASEYEAR;
 date.set(Calendar.YEAR, year + BASEYEAR - 1);
}

//sets the next year relative to the date already set(In constructor).
public synchronized void nextYear() {
 int year = date.get(Calendar.YEAR)-BASEYEAR;
 date.set(Calendar.YEAR, year + BASEYEAR + 1);
}

//sets the prev month relative to the date already set(In constructor).
public synchronized void prevMon() {
int month = date.get(Calendar.MONTH);
date.set(Calendar.MONTH, month - 1);
}

//sets the next month relative to the date already set(In constructor).
public synchronized void nextMon() {
 int month = date.get(Calendar.MONTH);
 date.set(Calendar.MONTH, month + 1);
}

//sets the prev day relative to the date already set(In constructor).
public synchronized void prevDay() {
 int day = date.get(Calendar.DAY_OF_MONTH);
 date.set(Calendar.DAY_OF_MONTH, day - 1);
}

//sets the next day relative to the date already set(In constructor).
public synchronized void nextDay() {
 int day = date.get(Calendar.DAY_OF_MONTH);
 date.set(Calendar.DAY_OF_MONTH, day + 1);
}

//sets the current system date, in case it is needed.
public static synchronized Date currentSystemDate() {
 return new Date();
}

//returns the date, after all the year,month,day operation.
public  synchronized Date getDate() {
 return date.getTime();
}
}

No comments: