Date calculations in Java

At some point of the development one way or the other we have to deal with date manipulation. In my current work we deal with lot of date manipulations. Here are some of the methods we use every day.

Creating a date as 1st of a given month:

public static Date firstOfMonth(final Date inputDate) {
final Calendar result = Calendar.getInstance();
result.setTime(inputDate);
result.set(Calendar.DAY_OF_MONTH, 1);
return result.getTime();
}

Creating a date as last day of a given month:

public static Date endOfMonth(final Date inputDate) {
final Calendar result = Calendar.getInstance();
result.setTime(inputDate);
result.set(Calendar.DAY_OF_MONTH, result.getActualMaximum(Calendar.DAY_OF_MONTH));
return result.getTime();
}

Calculating person’s age:


public static int getAge(final Date inputDate) {
final Calendar personDob = Calendar.getInstance();
personDob.setTime(inputDate);

final Calendar today = Calendar.getInstance();
return today.get(Calendar.YEAR) – personDob.get(Calendar.YEAR);
}

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s