Date handle functions in Java
I showed a small function about how to get a day of week based on the inputted date in my previous article. But there are still some more functions related to Date that i usually have to deal with, so i also want to share them here
1. Plus a date and a year
public static Date addYear(Date date, int value) {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(Calendar.YEAR, value);
return calendar.getTime();
}
2. Plus a date and a month
public static Date addMonth(Date date, int value) {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(Calendar.MONTH, value);
return calendar.getTime();
}
3. Plus a date and a day
public static Date addDay(Date date, int value) {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, value);
return calendar.getTime();
}
4. Plus a date and minute
public static Date addMinute(Date date, int value) {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(Calendar.MINUTE, value);
return calendar.getTime();
}
5. Calculate years old
// bornDate is a date string based on [yyyyMMdd] format
public static String calAge(String bornDate) throws Exception {
// If the input date is null
if (bornDate == null || bornDate.length() == 0) {
bornDate = "00000000";
}
Calendar cal = new GregorianCalendar(new Integer(bornDate.substring(0, 4)),
new Integer(bornDate.substring(4, 6)) - 1,
new Integer(bornDate.substring(6, 8)));
Calendar now = new GregorianCalendar();
int age = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
if(cal.get(Calendar.MONTH) > now.get(Calendar.MONTH)
|| (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH)
&& cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH))) {
age--;
}
return age + " years old";
}
6. Get first day of week
public static Date getFirstDayOfWeek(Date date) {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.set(
Calendar.DAY_OF_WEEK,
calendar.getActualMinimum(Calendar.DAY_OF_WEEK));
return calendar.getTime();
}
7. Get day of week
public static int getDayOfWeek(Date date) {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_WEEK);
}
8. Get first day of month
public static Date getFirstDayOfMonth(Date date) {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.set(
Calendar.DAY_OF_MONTH,
calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
return calendar.getTime();
}
9. Get last day of month
public static Date getLastDayOfMonth(Date date) {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.set(
Calendar.DAY_OF_MONTH,
calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
return calendar.getTime();
}
Advertisement
Categories: Java
Date function, Java
thanks for sharing this article.It is very informative and interesting.