Tuesday, August 30, 2011

Last Date Of Month - Java Implementation

A code snippet to set a Date object to the last date of the month:


Calendar cal = Calendar.getInstance();

cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));

System.out.println(cal.getTime());


The Calendar API has a lot of other utility methods that are very convenient when you need to work on dates.

Friday, April 1, 2011

Auto-Build Project in Eclipse using ANT

Eclipse allows you to set your custom ANT file to build your projects. Here's how you can configure the build process to pick your ANT file and not the default Java Builder.

> Right click on Project and select "Properties"

> On the Properties window, click on "Builders"

> Since you want to set your own build process, uncheck the "Java Builder"

> Now we need to configure the ANT file for the project build. Click "New",
select "Ant Builder" and click OK

> Enter a valid name for your builder, select the buildfile and the project root using the "Browse Workspace" button. Use can set a lot of other properties on this window to support the build process like "Arguments", "Targets", etc.

> Once you have your configurations set, click OK

> You should be back on the Builders window, check the builder you just created and click OK


You are now set with your ANT builder and you can view the build output in the console view.

Hope this helps.

Wednesday, January 26, 2011

Months between two dates - Java Implementation

A code snippet that will accept two java.util.Date objects and return the number of months between the two dates.

public int getNumberOfMonths(Date fromDate, Date toDate){
int monthCount=0;
Calendar cal = Calendar.getInstance();
cal.setTime(fromDate);
int c1date=cal.get(Calendar.DATE);
int c1month=cal.get(Calendar.MONTH);
int c1year=cal.get(Calendar.YEAR);
cal.setTime(toDate);
int c2date=cal.get(Calendar.DATE);
int c2month=cal.get(Calendar.MONTH);
int c2year=cal.get(Calendar.YEAR);

monthCount = ((c2year-c1year)*12) + (c2month-c1month) + ((c2date>=c1date)?1:0);

return monthCount;
}


Hope this helps!