Java Tutorial/Data Type/Date Calculation

Материал из Java эксперт
Версия от 15:27, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Содержание

Add 10 months to the calendar

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar cal = Calendar.getInstance();
    System.out.println("Today : " + cal.getTime());
    // Substract 30 days from the calendar
    cal.add(Calendar.DATE, -30);
    System.out.println("30 days ago: " + cal.getTime());
  }
}





add 8 days to the current date and print out the date and time

import java.text.DateFormat;
import java.util.Calendar;
public class CalendarManipulation {
  public static void main(String s[]) {
    Calendar cal = Calendar.getInstance();
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL,
        DateFormat.MEDIUM);
    System.out.println(df.format(cal.getTime()));
    cal.add(Calendar.DATE, 8);
    System.out.println(df.format(cal.getTime()));
  }
}





add another 12 hours and print out the date and time

import java.text.DateFormat;
import java.util.Calendar;
public class CalendarManipulation {
  public static void main(String s[]) {
    Calendar cal = Calendar.getInstance();
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL,
        DateFormat.MEDIUM);
    System.out.println(df.format(cal.getTime()));
    cal.add(Calendar.AM_PM, 1);
    System.out.println(df.format(cal.getTime()));
  }
}





Add hours, minutes or seconds to a date

import java.util.Calendar;
 
public class DateAddHour {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        System.out.println("Original = " + calendar.getTime());
 
        // Substract 2 hour from the current time
        calendar.add(Calendar.HOUR, -2);
 
        // Add 30 minutes to the calendar time
        calendar.add(Calendar.MINUTE, 30);
 
        // Add 300 seconds to the calendar time
        calendar.add(Calendar.SECOND, 300);
        System.out.println("Updated  = " + calendar.getTime());
    }
}





Add hours to current date using Calendar.add method

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current Date : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
    System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":"
        + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
     now.add(Calendar.HOUR, 10);
    System.out.println("New time after adding 10 hours : " + now.get(Calendar.HOUR_OF_DAY) + ":"
        + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
  }
}





Add minutes to current date using Calendar.add method

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":"
        + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
    now.add(Calendar.MINUTE, 20);
    System.out.println("New time after adding 20 minutes : " + now.get(Calendar.HOUR_OF_DAY) + ":"
        + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
  }
}





Add months to current date using Calendar.add method

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
    
    now.add(Calendar.MONTH, 10);
    System.out.println("date after 10 months : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
  }
}





Add or substract days to current date using Java Calendar

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
    // add days to current date using Calendar.add method
    now.add(Calendar.DATE, 1);
    System.out.println("date after one day : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
  }
}
/*
Current date : 2-20-2009
date after one day : 2-21-2009
*/





Add seconds to current date using Calendar.add method

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":"
        + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
    now.add(Calendar.SECOND, 100);
    System.out.println("New time after adding 100 seconds : " + now.get(Calendar.HOUR_OF_DAY) + ":"
        + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
  }
}





Add week to current date using Calendar.add method

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
    System.out.println("Current week of month is : " + now.get(Calendar.WEEK_OF_MONTH));
    System.out.println("Current week of year is : " + now.get(Calendar.WEEK_OF_YEAR));
    
    now.add(Calendar.WEEK_OF_YEAR, 1);
    System.out.println("date after one week : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
  }
}





Add year to current date using Calendar.add method

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
    
    now.add(Calendar.YEAR, 1);
    System.out.println("date after one year : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
  }
}





Calculate the age

import java.util.Calendar;
import java.util.GregorianCalendar;
public class Main {
  public static void main(String[] args) {
    Calendar cal = new GregorianCalendar(1999, 1, 1);
    Calendar now = new GregorianCalendar();
    int res = 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))) {
      res--;
    }
    System.out.println(res);
  }
}





Calendar adjust date automatically

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current Date : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
    System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":"
        + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
   System.out.println("New date after adding 10 hours : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));  }
}





Checks if two calendar objects represent the same local time.

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * A suite of utilities surrounding the use of the
 * {@link java.util.Calendar} and {@link java.util.Date} object.
 * 
 * DateUtils contains a lot of common methods considering manipulations
 * of Dates or Calendars. Some methods require some extra explanation.
 * The truncate and round methods could be considered the Math.floor(),
 * Math.ceil() or Math.round versions for dates
 * This way date-fields will be ignored in bottom-up order.
 * As a complement to these methods we"ve introduced some fragment-methods.
 * With these methods the Date-fields will be ignored in top-down order.
 * Since a date without a year is not a valid date, you have to decide in what
 * kind of date-field you want your result, for instance milliseconds or days.
 * 
 *   
 *   
 *
 * @author 
 * @author Phil Steitz
 * @author Robert Scholte
 * @since 2.0
 * @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
 */
public class Main {
  //-----------------------------------------------------------------------
  /**
   * Checks if two calendar objects represent the same local time.
   *
   * This method compares the values of the fields of the two objects.
   * In addition, both calendars must be the same of the same type.
   * 
   * @param cal1  the first calendar, not altered, not null
   * @param cal2  the second calendar, not altered, not null
   * @return true if they represent the same millisecond instant
   * @throws IllegalArgumentException if either date is <code>null</code>
   * @since 2.1
   */
  public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) {
      if (cal1 == null || cal2 == null) {
          throw new IllegalArgumentException("The date must not be null");
      }
      return (cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) &&
              cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) &&
              cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) &&
              cal1.get(Calendar.HOUR) == cal2.get(Calendar.HOUR) &&
              cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
              cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
              cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
              cal1.getClass() == cal2.getClass());
  }
}





Checks if two date objects are on the same day ignoring time

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * A suite of utilities surrounding the use of the
 * {@link java.util.Calendar} and {@link java.util.Date} object.
 * 
 * DateUtils contains a lot of common methods considering manipulations
 * of Dates or Calendars. Some methods require some extra explanation.
 * The truncate and round methods could be considered the Math.floor(),
 * Math.ceil() or Math.round versions for dates
 * This way date-fields will be ignored in bottom-up order.
 * As a complement to these methods we"ve introduced some fragment-methods.
 * With these methods the Date-fields will be ignored in top-down order.
 * Since a date without a year is not a valid date, you have to decide in what
 * kind of date-field you want your result, for instance milliseconds or days.
 * 
 *   
 *   
 *
 * @author 
 * @author Phil Steitz
 * @author Robert Scholte
 * @since 2.0
 * @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
 */
public class Main {
  //-----------------------------------------------------------------------
  /**
   * Checks if two date objects are on the same day ignoring time.
   *
   * 28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true.
   * 28 Mar 2002 13:45 and 12 Mar 2002 13:45 would return false.
   * 
   * 
   * @param date1  the first date, not altered, not null
   * @param date2  the second date, not altered, not null
   * @return true if they represent the same day
   * @throws IllegalArgumentException if either date is <code>null</code>
   * @since 2.1
   */
  public static boolean isSameDay(Date date1, Date date2) {
      if (date1 == null || date2 == null) {
          throw new IllegalArgumentException("The date must not be null");
      }
      Calendar cal1 = Calendar.getInstance();
      cal1.setTime(date1);
      Calendar cal2 = Calendar.getInstance();
      cal2.setTime(date2);
      return isSameDay(cal1, cal2);
  }
  /**
   * Checks if two calendar objects are on the same day ignoring time.
   *
   * 28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true.
   * 28 Mar 2002 13:45 and 12 Mar 2002 13:45 would return false.
   * 
   * 
   * @param cal1  the first calendar, not altered, not null
   * @param cal2  the second calendar, not altered, not null
   * @return true if they represent the same day
   * @throws IllegalArgumentException if either calendar is <code>null</code>
   * @since 2.1
   */
  public static boolean isSameDay(Calendar cal1, Calendar cal2) {
      if (cal1 == null || cal2 == null) {
          throw new IllegalArgumentException("The date must not be null");
      }
      return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
              cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
              cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
  }
}





Checks if two date objects represent the same instant in time

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * A suite of utilities surrounding the use of the
 * {@link java.util.Calendar} and {@link java.util.Date} object.
 * 
 * DateUtils contains a lot of common methods considering manipulations
 * of Dates or Calendars. Some methods require some extra explanation.
 * The truncate and round methods could be considered the Math.floor(),
 * Math.ceil() or Math.round versions for dates
 * This way date-fields will be ignored in bottom-up order.
 * As a complement to these methods we"ve introduced some fragment-methods.
 * With these methods the Date-fields will be ignored in top-down order.
 * Since a date without a year is not a valid date, you have to decide in what
 * kind of date-field you want your result, for instance milliseconds or days.
 * 
 *   
 *   
 *
 * @author 
 * @author Phil Steitz
 * @author Robert Scholte
 * @since 2.0
 * @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
 */
public class Main {

  //-----------------------------------------------------------------------
  /**
   * Checks if two date objects represent the same instant in time.
   *
   * This method compares the long millisecond time of the two objects.
   * 
   * @param date1  the first date, not altered, not null
   * @param date2  the second date, not altered, not null
   * @return true if they represent the same millisecond instant
   * @throws IllegalArgumentException if either date is <code>null</code>
   * @since 2.1
   */
  public static boolean isSameInstant(Date date1, Date date2) {
      if (date1 == null || date2 == null) {
          throw new IllegalArgumentException("The date must not be null");
      }
      return date1.getTime() == date2.getTime();
  }
  /**
   * Checks if two calendar objects represent the same instant in time.
   *
   * This method compares the long millisecond time of the two objects.
   * 
   * @param cal1  the first calendar, not altered, not null
   * @param cal2  the second calendar, not altered, not null
   * @return true if they represent the same millisecond instant
   * @throws IllegalArgumentException if either date is <code>null</code>
   * @since 2.1
   */
  public static boolean isSameInstant(Calendar cal1, Calendar cal2) {
      if (cal1 == null || cal2 == null) {
          throw new IllegalArgumentException("The date must not be null");
      }
      return cal1.getTime().getTime() == cal2.getTime().getTime();
  }
}





Compare date time using after method of Java Calendar

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar futureCal = Calendar.getInstance();
    futureCal.set(Calendar.YEAR, 3000);
    Calendar now = Calendar.getInstance();
    System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
    System.out.println("Is futureCal after now ? : " + futureCal.after(now));
  }
}





Compare date time using before method of Java Calendar

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar old = Calendar.getInstance();
    old.set(Calendar.YEAR, 2990);
    Calendar now = Calendar.getInstance();
    System.out.println("Is old before now ? : " + old.before(now));
  }
}





Compute days between 2 dates

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Main{
  public static void main(String args[]) {
    Calendar c1 = new GregorianCalendar();
    Calendar c2 = new GregorianCalendar();
    c1.set(2000, 12, 12, 0, 0, 0);
    c2.set(2001, 12, 12, 0, 0, 0);
    System.out.println(daysBetween(c1.getTime(), c2.getTime()) + " day(s) between " + args[0] + "-"
        + args[1] + "-" + args[2] + " and " + args[3] + "-" + args[4] + "-" + args[5]);
  }
  static final long ONE_HOUR = 60 * 60 * 1000L;
  public static long daysBetween(Date d1, Date d2) {
    return ((d2.getTime() - d1.getTime() + ONE_HOUR) / (ONE_HOUR * 24));
  }
}





Convert day of year to day of month

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, 2007);
    cal.set(Calendar.DAY_OF_YEAR, 180);
    System.out.println("Calendar date is: " + cal.getTime());
    int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
    System.out.println("Calendar day of month: " + dayOfMonth);
    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
    System.out.println("Calendar day of week: " + dayOfWeek);
  }
}





Days Till End Of Year

import java.util.Calendar;
import java.util.GregorianCalendar;
class Main {
  public static void main(String args[]) {
    Calendar calendar1 = Calendar.getInstance();
    int currentDayOfYear = calendar1.get(Calendar.DAY_OF_YEAR);
    int year = calendar1.get(Calendar.YEAR);
    Calendar calendar2 = new GregorianCalendar(year, 11, 31);
    int dayDecember31 = calendar2.get(Calendar.DAY_OF_YEAR);
    int days = dayDecember31 - currentDayOfYear;
    System.out.println(days + " days remain in current year");
  }
}





Determine if an hour is between an interval

import java.text.SimpleDateFormat;
 
public class Main{
    static String  HOUR_FORMAT = "HH:mm";
    static SimpleDateFormat sdfHour = new SimpleDateFormat(HOUR_FORMAT);
    public static boolean isHourInInterval(String target, String start, String end) {
        return ((target.rupareTo(start) >= 0)&& (target.rupareTo(end) <= 0));
    }
    public static void main (String[] args) {
      String now = "12";
      String start = "14:00";
      String end   = "14:26";
      System. out.println(now + " between " + start + "-" + end + "?");
      System. out.println(isHourInInterval(now,start,end));
    }
   
}





Determining If a Year Is a Leap Year

import java.util.GregorianCalendar;
public class Main {
  public static void main(String[] argv) throws Exception {
    GregorianCalendar cal = new GregorianCalendar();
    boolean b = cal.isLeapYear(1998); // false
    b = cal.isLeapYear(2000); // true
    b = cal.isLeapYear(0); // true
  }
}





Determining the Day-of-Week for a Particular Date

import java.util.Calendar;
import java.util.GregorianCalendar;
public class Main {
  public static void main(String[] argv) throws Exception {
    Calendar xmas = new GregorianCalendar(1998, Calendar.DECEMBER, 25);
    int dayOfWeek = xmas.get(Calendar.DAY_OF_WEEK); // 6=Friday
    Calendar cal = new GregorianCalendar(2003, Calendar.JANUARY, 1);
    dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 4=Wednesday
  }
}





Find the Difference Between Two Given Dates

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class MainClass {
  public static int diff(Date date1, Date date2) {
    Calendar c1 = Calendar.getInstance();
    Calendar c2 = Calendar.getInstance();
    c1.setTime(date1);
    c2.setTime(date2);
    int diffDay = 0;
    if (c1.before(c2)) {
      diffDay = countDiffDay(c1, c2);
    } else {
      diffDay = countDiffDay(c2, c1);
    }
    return diffDay;
  }
  public static void DateDiff(Date date1, Date date2) {
    int diffDay = diff(date1, date2);
    System.out.println("Different Day : " + diffDay);
  }
  public static int countDiffDay(Calendar c1, Calendar c2) {
    int returnInt = 0;
    while (!c1.after(c2)) {
      c1.add(Calendar.DAY_OF_MONTH, 1);
      returnInt++;
    }
    if (returnInt > 0) {
      returnInt = returnInt - 1;
    }
    return (returnInt);
  }
  public static Date makeDate(String dateString) throws Exception {
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    return formatter.parse(dateString);
  }
  public static void main(String argv[]) throws Exception {
    Calendar cc1 = Calendar.getInstance();
    Calendar cc2 = Calendar.getInstance();
    cc1.add(Calendar.DAY_OF_MONTH, 10);
    DateDiff(cc1.getTime(), cc2.getTime());
    java.util.Date d1 = makeDate("10/10/2000");
    java.util.Date d2 = makeDate("10/18/2000");
    DateDiff(d1, d2);
    java.util.Date d3 = makeDate("1/1/2000");
    java.util.Date d4 = makeDate("12/31/2000");
    int diff34 = diff(d3, d4);
    System.out.println("diff34=" + diff34);
  }
}





If a date is after another date

import java.util.Calendar;
import java.util.Date;
public class Main {
  public static void main(String[] args) {
    Date today = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, 1);
    Date tomorrow = calendar.getTime();
    if (tomorrow.after(today)) {
      System.out.println(tomorrow + " is after " + today);
    }
  }
}





If a date is before another date

import java.util.Calendar;
import java.util.Date;
public class Main {
  public static void main(String[] args) {
    Date today = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, -1);
    Date yesterday = calendar.getTime();
    if (yesterday.before(today)) {
      System.out.println(yesterday + " is before " + today);
    }
  }
}





Increment and Decrement a Date Using the Calendar Class

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar cal = Calendar.getInstance();
    System.out.println("Now : " + cal.getTime());
    int daysToIncrement = 5;
    cal.add(Calendar.DATE, daysToIncrement);
    System.out.println("Date after increment: " + cal.getTime());
  }
}





Increment and Decrement Months Using the Calendar Class

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar cal = Calendar.getInstance();
    System.out.println("Now : " + cal.getTime());
    int monthsToDecrement = -1;
    cal.add(Calendar.MONTH, monthsToDecrement);
    System.out.println("Date after decrement: " + cal.getTime());
  }
}
/*Now : Wed Feb 18 13:52:43 PST 2009
Date after decrement: Sun Jan 18 13:52:43 PST 2009
*/





Returns a Date set just to Noon, to the closest possible millisecond of the day.

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  The ASF licenses this file to You
 * under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.  For additional information regarding
 * copyright in this work, please see the NOTICE file in the top level
 * directory of this distribution.
 */
import java.util.Calendar;
import java.util.Date;
public class Utils {
  /**
   * Returns a Date set just to Noon, to the closest possible millisecond
   * of the day. If a null day is passed in, a new Date is created.
   * nnoon (00m 12h 00s)
   */
  public static Date getNoonOfDay(Date day, Calendar cal) {
      if (day == null) day = new Date();
      cal.setTime(day);
      cal.set(Calendar.HOUR_OF_DAY, 12);
      cal.set(Calendar.MINUTE,      cal.getMinimum(Calendar.MINUTE));
      cal.set(Calendar.SECOND,      cal.getMinimum(Calendar.SECOND));
      cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));
      return cal.getTime();
  }
}





Returns a Date set to the first possible millisecond of the day, just after midnight.

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  The ASF licenses this file to You
 * under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.  For additional information regarding
 * copyright in this work, please see the NOTICE file in the top level
 * directory of this distribution.
 */
import java.util.Calendar;
import java.util.Date;
public class Utils {
  /**
   * Returns a Date set to the first possible millisecond of the day, just
   * after midnight. If a null day is passed in, a new Date is created.
   * midnight (00m 00h 00s)
   */
  public static Date getStartOfDay(Date day) {
      return getStartOfDay(day, Calendar.getInstance());
  }
  
  
  /**
   * Returns a Date set to the first possible millisecond of the day, just
   * after midnight. If a null day is passed in, a new Date is created.
   * midnight (00m 00h 00s)
   */
  public static Date getStartOfDay(Date day, Calendar cal) {
      if (day == null) day = new Date();
      cal.setTime(day);
      cal.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR_OF_DAY));
      cal.set(Calendar.MINUTE,      cal.getMinimum(Calendar.MINUTE));
      cal.set(Calendar.SECOND,      cal.getMinimum(Calendar.SECOND));
      cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));
      return cal.getTime();
  }
}





Returns a Date set to the first possible millisecond of the month, just after midnight.

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  The ASF licenses this file to You
 * under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.  For additional information regarding
 * copyright in this work, please see the NOTICE file in the top level
 * directory of this distribution.
 */
import java.util.Calendar;
import java.util.Date;
public class Utils {
  /**
   * Returns a Date set to the first possible millisecond of the month, just
   * after midnight. If a null day is passed in, a new Date is created.
   * midnight (00m 00h 00s)
   */
  public static Date getStartOfMonth(Date day) {
      return getStartOfMonth(day, Calendar.getInstance());
  }
  
  
  public static Date getStartOfMonth(Date day, Calendar cal) {
      if (day == null) day = new Date();
      cal.setTime(day);
      
      // set time to start of day
      cal.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR_OF_DAY));
      cal.set(Calendar.MINUTE,      cal.getMinimum(Calendar.MINUTE));
      cal.set(Calendar.SECOND,      cal.getMinimum(Calendar.SECOND));
      cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));
      
      // set time to first day of month
      cal.set(Calendar.DAY_OF_MONTH, 1);
      
      return cal.getTime();
  }
}





Returns a Date set to the last possible millisecond of the day, just before midnight.

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  The ASF licenses this file to You
 * under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.  For additional information regarding
 * copyright in this work, please see the NOTICE file in the top level
 * directory of this distribution.
 */
import java.util.Calendar;
import java.util.Date;
public class Utils {
  /**
   * Returns a Date set to the last possible millisecond of the day, just
   * before midnight. If a null day is passed in, a new Date is created.
   * midnight (00m 00h 00s)
   */
  public static Date getEndOfDay(Date day) {
      return getEndOfDay(day,Calendar.getInstance());
  }
  
  
  public static Date getEndOfDay(Date day,Calendar cal) {
      if (day == null) day = new Date();
      cal.setTime(day);
      cal.set(Calendar.HOUR_OF_DAY, cal.getMaximum(Calendar.HOUR_OF_DAY));
      cal.set(Calendar.MINUTE,      cal.getMaximum(Calendar.MINUTE));
      cal.set(Calendar.SECOND,      cal.getMaximum(Calendar.SECOND));
      cal.set(Calendar.MILLISECOND, cal.getMaximum(Calendar.MILLISECOND));
      return cal.getTime();
  }

}





Returns a Date set to the last possible millisecond of the minute.

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  The ASF licenses this file to You
 * under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.  For additional information regarding
 * copyright in this work, please see the NOTICE file in the top level
 * directory of this distribution.
 */
import java.util.Calendar;
import java.util.Date;
public class Utils {
  /**
   * Returns a Date set to the last possible millisecond of the minute.
   * If a null day is passed in, a new Date is created.
   */
  public static Date getEndOfMinute(Date day) {
      return getEndOfMinute(day, Calendar.getInstance());
  }
  
  
  public static Date getEndOfMinute(Date day, Calendar cal) {
      if (day == null || cal == null) {
          return day;
      }
      
      cal.setTime(day);
      cal.set(Calendar.SECOND,      cal.getMaximum(Calendar.SECOND));
      cal.set(Calendar.MILLISECOND, cal.getMaximum(Calendar.MILLISECOND));
      return cal.getTime();
  }
}





Returns a Date set to the last possible millisecond of the month, just before midnight.

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  The ASF licenses this file to You
 * under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.  For additional information regarding
 * copyright in this work, please see the NOTICE file in the top level
 * directory of this distribution.
 */
import java.util.Calendar;
import java.util.Date;
public class Utils {
  /**
   * Returns a Date set to the last possible millisecond of the month, just
   * before midnight. If a null day is passed in, a new Date is created.
   * midnight (00m 00h 00s)
   */
  public static Date getEndOfMonth(Date day) {
      return getEndOfMonth(day, Calendar.getInstance());
  }
  
  
  public static Date getEndOfMonth(Date day,Calendar cal) {
      if (day == null) day = new Date();
      cal.setTime(day);
      
      // set time to end of day
      cal.set(Calendar.HOUR_OF_DAY, cal.getMaximum(Calendar.HOUR_OF_DAY));
      cal.set(Calendar.MINUTE,      cal.getMaximum(Calendar.MINUTE));
      cal.set(Calendar.SECOND,      cal.getMaximum(Calendar.SECOND));
      cal.set(Calendar.MILLISECOND, cal.getMaximum(Calendar.MILLISECOND));
      
      // set time to first day of month
      cal.set(Calendar.DAY_OF_MONTH, 1);
      
      // add one month
      cal.add(Calendar.MONTH, 1);
      
      // back up one day
      cal.add(Calendar.DAY_OF_MONTH, -1);
      
      return cal.getTime();
  }
}





Returns the number of days within the fragment.

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.TimeZone;

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * A suite of utilities surrounding the use of the
 * {@link java.util.Calendar} and {@link java.util.Date} object.
 * 
 * DateUtils contains a lot of common methods considering manipulations
 * of Dates or Calendars. Some methods require some extra explanation.
 * The truncate and round methods could be considered the Math.floor(),
 * Math.ceil() or Math.round versions for dates
 * This way date-fields will be ignored in bottom-up order.
 * As a complement to these methods we"ve introduced some fragment-methods.
 * With these methods the Date-fields will be ignored in top-down order.
 * Since a date without a year is not a valid date, you have to decide in what
 * kind of date-field you want your result, for instance milliseconds or days.
 * 
 *   
 *   
 *
 * @author 
 * @author Phil Steitz
 * @author Robert Scholte
 * @since 2.0
 * @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
 */
public class Main {
  
  /**
   * The UTC time zone  (often referred to as GMT).
   */
  public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
  /**
   * Number of milliseconds in a standard second.
   * @since 2.1
   */
  public static final long MILLIS_PER_SECOND = 1000;
  /**
   * Number of milliseconds in a standard minute.
   * @since 2.1
   */
  public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
  /**
   * Number of milliseconds in a standard hour.
   * @since 2.1
   */
  public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
  /**
   * Number of milliseconds in a standard day.
   * @since 2.1
   */
  public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
  /**
   * This is half a month, so this represents whether a date is in the top
   * or bottom half of the month.
   */
  public final static int SEMI_MONTH = 1001;
  private static final int[][] fields = {
          {Calendar.MILLISECOND},
          {Calendar.SECOND},
          {Calendar.MINUTE},
          {Calendar.HOUR_OF_DAY, Calendar.HOUR},
          {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM 
              /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
          },
          {Calendar.MONTH, DateUtils.SEMI_MONTH},
          {Calendar.YEAR},
          {Calendar.ERA}};
  /**
   * A week range, starting on Sunday.
   */
  public final static int RANGE_WEEK_SUNDAY = 1;
  /**
   * A week range, starting on Monday.
   */
  public final static int RANGE_WEEK_MONDAY = 2;
  /**
   * A week range, starting on the day focused.
   */
  public final static int RANGE_WEEK_RELATIVE = 3;
  /**
   * A week range, centered around the day focused.
   */
  public final static int RANGE_WEEK_CENTER = 4;
  /**
   * A month range, the week starting on Sunday.
   */
  public final static int RANGE_MONTH_SUNDAY = 5;
  /**
   * A month range, the week starting on Monday.
   */
  public final static int RANGE_MONTH_MONDAY = 6;
  
  /**
   * Returns the number of days within the 
   * fragment. All datefields greater than the fragment will be ignored. 
   * 
   * Asking the days of any date will only return the number of days
   * of the current month (resulting in a number between 1 and 31). This 
   * method will retrieve the number of days for any fragment. 
   * For example, if you want to calculate the number of days past this year, 
   * your fragment is Calendar.YEAR. The result will be all days of the 
   * past month(s). 
   * 
   * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both 
   * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, 
   * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND
   * A fragment less than or equal to a DAY field will return 0. 
   * 
   * 
   * <ul>
   *  <li>January 28, 2008 with Calendar.MONTH as fragment will return 28
   *   (equivalent to calendar.get(Calendar.DAY_OF_MONTH))</li>
   *  <li>February 28, 2008 with Calendar.MONTH as fragment will return 28
   *   (equivalent to calendar.get(Calendar.DAY_OF_MONTH))</li>
   *  <li>January 28, 2008 with Calendar.YEAR as fragment will return 28
   *   (equivalent to calendar.get(Calendar.DAY_OF_YEAR))</li>
   *  <li>February 28, 2008 with Calendar.YEAR as fragment will return 59
   *   (equivalent to calendar.get(Calendar.DAY_OF_YEAR))</li>
   *  <li>January 28, 2008 with Calendar.MILLISECOND as fragment will return 0
   *   (a millisecond cannot be split in days)</li>
   * </ul>
   * 
   * 
   * @param calendar the calendar to work with, not null
   * @param fragment the Calendar field part of calendar to calculate 
   * @return number of days within the fragment of date
   * @throws IllegalArgumentException if the date is <code>null</code> or 
   * fragment is not supported
   * @since 2.4
   */
  public static long getFragmentInDays(Calendar calendar, int fragment) {
      return getFragment(calendar, fragment, Calendar.DAY_OF_YEAR);
  }
  
  
  /**
   * Date-version for fragment-calculation in any unit
   * 
   * @param date the date to work with, not null
   * @param fragment the Calendar field part of date to calculate 
   * @param unit Calendar field defining the unit
   * @return number of units within the fragment of the date
   * @throws IllegalArgumentException if the date is <code>null</code> or 
   * fragment is not supported
   * @since 2.4
   */
  private static long getFragment(Date date, int fragment, int unit) {
      if(date == null) {
          throw  new IllegalArgumentException("The date must not be null");
      }
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(date);
      return getFragment(calendar, fragment, unit);
  }
  /**
   * Calendar-version for fragment-calculation in any unit
   * 
   * @param calendar the calendar to work with, not null
   * @param fragment the Calendar field part of calendar to calculate 
   * @param unit Calendar field defining the unit
   * @return number of units within the fragment of the calendar
   * @throws IllegalArgumentException if the date is <code>null</code> or 
   * fragment is not supported
   * @since 2.4
   */
  private static long getFragment(Calendar calendar, int fragment, int unit) {
      if(calendar == null) {
          throw  new IllegalArgumentException("The date must not be null"); 
      }
      long millisPerUnit = getMillisPerUnit(unit);
      long result = 0;
      
      // Fragments bigger than a day require a breakdown to days
      switch (fragment) {
          case Calendar.YEAR:
              result += (calendar.get(Calendar.DAY_OF_YEAR) * MILLIS_PER_DAY) / millisPerUnit;
              break;
          case Calendar.MONTH:
              result += (calendar.get(Calendar.DAY_OF_MONTH) * MILLIS_PER_DAY) / millisPerUnit;
              break;
      }
      switch (fragment) {
          // Number of days already calculated for these cases
          case Calendar.YEAR:
          case Calendar.MONTH:
          
          // The rest of the valid cases
          case Calendar.DAY_OF_YEAR:
          case Calendar.DATE:
              result += (calendar.get(Calendar.HOUR_OF_DAY) * MILLIS_PER_HOUR) / millisPerUnit;
          case Calendar.HOUR_OF_DAY:
              result += (calendar.get(Calendar.MINUTE) * MILLIS_PER_MINUTE) / millisPerUnit;
          case Calendar.MINUTE:
              result += (calendar.get(Calendar.SECOND) * MILLIS_PER_SECOND) / millisPerUnit;
          case Calendar.SECOND:
              result += (calendar.get(Calendar.MILLISECOND) * 1) / millisPerUnit;
              break;
          case Calendar.MILLISECOND: break;//never useful
              default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported");
      }
      return result;
  }
  /**
   * Returns the number of millis of a datefield, if this is a constant value
   * 
   * @param unit A Calendar field which is a valid unit for a fragment
   * @return number of millis
   * @throws IllegalArgumentException if date can"t be represented in millisenconds
   * @since 2.4 
   */
  private static long getMillisPerUnit(int unit) {
      long result = Long.MAX_VALUE;
      switch (unit) {
          case Calendar.DAY_OF_YEAR:
          case Calendar.DATE:
              result = MILLIS_PER_DAY;
              break;
          case Calendar.HOUR_OF_DAY:
              result = MILLIS_PER_HOUR;
              break;
          case Calendar.MINUTE:
              result = MILLIS_PER_MINUTE;
              break;
          case Calendar.SECOND:
              result = MILLIS_PER_SECOND;
              break;
          case Calendar.MILLISECOND:
              result = 1;
              break;
          default: throw new IllegalArgumentException("The unit " + unit + " cannot be represented is milleseconds");
      }
      return result;
  }
}





Returns the number of hours within the fragment.

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.TimeZone;

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * A suite of utilities surrounding the use of the
 * {@link java.util.Calendar} and {@link java.util.Date} object.
 * 
 * DateUtils contains a lot of common methods considering manipulations
 * of Dates or Calendars. Some methods require some extra explanation.
 * The truncate and round methods could be considered the Math.floor(),
 * Math.ceil() or Math.round versions for dates
 * This way date-fields will be ignored in bottom-up order.
 * As a complement to these methods we"ve introduced some fragment-methods.
 * With these methods the Date-fields will be ignored in top-down order.
 * Since a date without a year is not a valid date, you have to decide in what
 * kind of date-field you want your result, for instance milliseconds or days.
 * 
 *   
 *   
 *
 * @author 
 * @author Phil Steitz
 * @author Robert Scholte
 * @since 2.0
 * @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
 */
public class Main {
  
  /**
   * The UTC time zone  (often referred to as GMT).
   */
  public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
  /**
   * Number of milliseconds in a standard second.
   * @since 2.1
   */
  public static final long MILLIS_PER_SECOND = 1000;
  /**
   * Number of milliseconds in a standard minute.
   * @since 2.1
   */
  public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
  /**
   * Number of milliseconds in a standard hour.
   * @since 2.1
   */
  public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
  /**
   * Number of milliseconds in a standard day.
   * @since 2.1
   */
  public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
  /**
   * This is half a month, so this represents whether a date is in the top
   * or bottom half of the month.
   */
  public final static int SEMI_MONTH = 1001;
  private static final int[][] fields = {
          {Calendar.MILLISECOND},
          {Calendar.SECOND},
          {Calendar.MINUTE},
          {Calendar.HOUR_OF_DAY, Calendar.HOUR},
          {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM 
              /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
          },
          {Calendar.MONTH, DateUtils.SEMI_MONTH},
          {Calendar.YEAR},
          {Calendar.ERA}};
  /**
   * A week range, starting on Sunday.
   */
  public final static int RANGE_WEEK_SUNDAY = 1;
  /**
   * A week range, starting on Monday.
   */
  public final static int RANGE_WEEK_MONDAY = 2;
  /**
   * A week range, starting on the day focused.
   */
  public final static int RANGE_WEEK_RELATIVE = 3;
  /**
   * A week range, centered around the day focused.
   */
  public final static int RANGE_WEEK_CENTER = 4;
  /**
   * A month range, the week starting on Sunday.
   */
  public final static int RANGE_MONTH_SUNDAY = 5;
  /**
   * A month range, the week starting on Monday.
   */
  public final static int RANGE_MONTH_MONDAY = 6;
  
  
  /**
   * Returns the number of hours within the 
   * fragment. All datefields greater than the fragment will be ignored. 
   * 
   * Asking the hours of any date will only return the number of hours
   * of the current day (resulting in a number between 0 and 23). This 
   * method will retrieve the number of hours for any fragment. 
   * For example, if you want to calculate the number of hours past this month, 
   * your fragment is Calendar.MONTH. The result will be all hours of the 
   * past day(s). 
   * 
   * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both 
   * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, 
   * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND
   * A fragment less than or equal to a HOUR field will return 0. 
   * 
   * 
   * <ul>
   *  <li>January 1, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 7
   *   (equivalent to deprecated date.getHours())</li>
   *  <li>January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 7
   *   (equivalent to deprecated date.getHours())</li>
   *  <li>January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 7</li>
   *  <li>January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 127 (5*24 + 7)</li>
   *  <li>January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0
   *   (a millisecond cannot be split in hours)</li>
   * </ul>
   * 
   * 
   * @param date the date to work with, not null
   * @param fragment the Calendar field part of date to calculate 
   * @return number of hours within the fragment of date
   * @throws IllegalArgumentException if the date is <code>null</code> or 
   * fragment is not supported
   * @since 2.4
   */
  public static long getFragmentInHours(Date date, int fragment) {
      return getFragment(date, fragment, Calendar.HOUR_OF_DAY);
  }
  
  
  
  /**
   * Date-version for fragment-calculation in any unit
   * 
   * @param date the date to work with, not null
   * @param fragment the Calendar field part of date to calculate 
   * @param unit Calendar field defining the unit
   * @return number of units within the fragment of the date
   * @throws IllegalArgumentException if the date is <code>null</code> or 
   * fragment is not supported
   * @since 2.4
   */
  private static long getFragment(Date date, int fragment, int unit) {
      if(date == null) {
          throw  new IllegalArgumentException("The date must not be null");
      }
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(date);
      return getFragment(calendar, fragment, unit);
  }
  /**
   * Calendar-version for fragment-calculation in any unit
   * 
   * @param calendar the calendar to work with, not null
   * @param fragment the Calendar field part of calendar to calculate 
   * @param unit Calendar field defining the unit
   * @return number of units within the fragment of the calendar
   * @throws IllegalArgumentException if the date is <code>null</code> or 
   * fragment is not supported
   * @since 2.4
   */
  private static long getFragment(Calendar calendar, int fragment, int unit) {
      if(calendar == null) {
          throw  new IllegalArgumentException("The date must not be null"); 
      }
      long millisPerUnit = getMillisPerUnit(unit);
      long result = 0;
      
      // Fragments bigger than a day require a breakdown to days
      switch (fragment) {
          case Calendar.YEAR:
              result += (calendar.get(Calendar.DAY_OF_YEAR) * MILLIS_PER_DAY) / millisPerUnit;
              break;
          case Calendar.MONTH:
              result += (calendar.get(Calendar.DAY_OF_MONTH) * MILLIS_PER_DAY) / millisPerUnit;
              break;
      }
      switch (fragment) {
          // Number of days already calculated for these cases
          case Calendar.YEAR:
          case Calendar.MONTH:
          
          // The rest of the valid cases
          case Calendar.DAY_OF_YEAR:
          case Calendar.DATE:
              result += (calendar.get(Calendar.HOUR_OF_DAY) * MILLIS_PER_HOUR) / millisPerUnit;
          case Calendar.HOUR_OF_DAY:
              result += (calendar.get(Calendar.MINUTE) * MILLIS_PER_MINUTE) / millisPerUnit;
          case Calendar.MINUTE:
              result += (calendar.get(Calendar.SECOND) * MILLIS_PER_SECOND) / millisPerUnit;
          case Calendar.SECOND:
              result += (calendar.get(Calendar.MILLISECOND) * 1) / millisPerUnit;
              break;
          case Calendar.MILLISECOND: break;//never useful
              default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported");
      }
      return result;
  }
  /**
   * Returns the number of millis of a datefield, if this is a constant value
   * 
   * @param unit A Calendar field which is a valid unit for a fragment
   * @return number of millis
   * @throws IllegalArgumentException if date can"t be represented in millisenconds
   * @since 2.4 
   */
  private static long getMillisPerUnit(int unit) {
      long result = Long.MAX_VALUE;
      switch (unit) {
          case Calendar.DAY_OF_YEAR:
          case Calendar.DATE:
              result = MILLIS_PER_DAY;
              break;
          case Calendar.HOUR_OF_DAY:
              result = MILLIS_PER_HOUR;
              break;
          case Calendar.MINUTE:
              result = MILLIS_PER_MINUTE;
              break;
          case Calendar.SECOND:
              result = MILLIS_PER_SECOND;
              break;
          case Calendar.MILLISECOND:
              result = 1;
              break;
          default: throw new IllegalArgumentException("The unit " + unit + " cannot be represented is milleseconds");
      }
      return result;
  }
}





Returns the number of milliseconds within the fragment.

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.TimeZone;

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * A suite of utilities surrounding the use of the
 * {@link java.util.Calendar} and {@link java.util.Date} object.
 * 
 * DateUtils contains a lot of common methods considering manipulations
 * of Dates or Calendars. Some methods require some extra explanation.
 * The truncate and round methods could be considered the Math.floor(),
 * Math.ceil() or Math.round versions for dates
 * This way date-fields will be ignored in bottom-up order.
 * As a complement to these methods we"ve introduced some fragment-methods.
 * With these methods the Date-fields will be ignored in top-down order.
 * Since a date without a year is not a valid date, you have to decide in what
 * kind of date-field you want your result, for instance milliseconds or days.
 * 
 *   
 *   
 *
 * @author 
 * @author Phil Steitz
 * @author Robert Scholte
 * @since 2.0
 * @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
 */
public class Main {
  
  /**
   * The UTC time zone  (often referred to as GMT).
   */
  public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
  /**
   * Number of milliseconds in a standard second.
   * @since 2.1
   */
  public static final long MILLIS_PER_SECOND = 1000;
  /**
   * Number of milliseconds in a standard minute.
   * @since 2.1
   */
  public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
  /**
   * Number of milliseconds in a standard hour.
   * @since 2.1
   */
  public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
  /**
   * Number of milliseconds in a standard day.
   * @since 2.1
   */
  public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
  /**
   * This is half a month, so this represents whether a date is in the top
   * or bottom half of the month.
   */
  public final static int SEMI_MONTH = 1001;
  private static final int[][] fields = {
          {Calendar.MILLISECOND},
          {Calendar.SECOND},
          {Calendar.MINUTE},
          {Calendar.HOUR_OF_DAY, Calendar.HOUR},
          {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM 
              /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
          },
          {Calendar.MONTH, DateUtils.SEMI_MONTH},
          {Calendar.YEAR},
          {Calendar.ERA}};
  /**
   * A week range, starting on Sunday.
   */
  public final static int RANGE_WEEK_SUNDAY = 1;
  /**
   * A week range, starting on Monday.
   */
  public final static int RANGE_WEEK_MONDAY = 2;
  /**
   * A week range, starting on the day focused.
   */
  public final static int RANGE_WEEK_RELATIVE = 3;
  /**
   * A week range, centered around the day focused.
   */
  public final static int RANGE_WEEK_CENTER = 4;
  /**
   * A month range, the week starting on Sunday.
   */
  public final static int RANGE_MONTH_SUNDAY = 5;
  /**
   * A month range, the week starting on Monday.
   */
  public final static int RANGE_MONTH_MONDAY = 6;
  

  /**
   * Returns the number of milliseconds within the 
   * fragment. All datefields greater than the fragment will be ignored. 
   * 
   * Asking the milliseconds of any date will only return the number of milliseconds
   * of the current second (resulting in a number between 0 and 999). This 
   * method will retrieve the number of milliseconds for any fragment. 
   * For example, if you want to calculate the number of seconds past today, 
   * your fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will
   * be all seconds of the past hour(s), minutes(s) and second(s). 
   * 
   * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both 
   * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, 
   * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND
   * A fragment less than or equal to a MILLISECOND field will return 0. 
   * 
   * 
   * <ul>
   *  <li>January 1, 2008 7:15:10.538 with Calendar.SECOND as fragment will return 538
   *   (equivalent to calendar.get(Calendar.MILLISECOND))</li>
   *  <li>January 6, 2008 7:15:10.538 with Calendar.SECOND as fragment will return 538
   *   (equivalent to calendar.get(Calendar.MILLISECOND))</li>
   *  <li>January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10538
   *   (10*1000 + 538)</li>
   *  <li>January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0
   *   (a millisecond cannot be split in milliseconds)</li>
   * </ul>
   * 
   * 
   * @param calendar the calendar to work with, not null
   * @param fragment the Calendar field part of calendar to calculate 
   * @return number of milliseconds within the fragment of date
   * @throws IllegalArgumentException if the date is <code>null</code> or 
   * fragment is not supported
   * @since 2.4
   */
public static long getFragmentInMilliseconds(Calendar calendar, int fragment) {
  return getFragment(calendar, fragment, Calendar.MILLISECOND);
}
  
  /**
   * Date-version for fragment-calculation in any unit
   * 
   * @param date the date to work with, not null
   * @param fragment the Calendar field part of date to calculate 
   * @param unit Calendar field defining the unit
   * @return number of units within the fragment of the date
   * @throws IllegalArgumentException if the date is <code>null</code> or 
   * fragment is not supported
   * @since 2.4
   */
  private static long getFragment(Date date, int fragment, int unit) {
      if(date == null) {
          throw  new IllegalArgumentException("The date must not be null");
      }
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(date);
      return getFragment(calendar, fragment, unit);
  }
  /**
   * Calendar-version for fragment-calculation in any unit
   * 
   * @param calendar the calendar to work with, not null
   * @param fragment the Calendar field part of calendar to calculate 
   * @param unit Calendar field defining the unit
   * @return number of units within the fragment of the calendar
   * @throws IllegalArgumentException if the date is <code>null</code> or 
   * fragment is not supported
   * @since 2.4
   */
  private static long getFragment(Calendar calendar, int fragment, int unit) {
      if(calendar == null) {
          throw  new IllegalArgumentException("The date must not be null"); 
      }
      long millisPerUnit = getMillisPerUnit(unit);
      long result = 0;
      
      // Fragments bigger than a day require a breakdown to days
      switch (fragment) {
          case Calendar.YEAR:
              result += (calendar.get(Calendar.DAY_OF_YEAR) * MILLIS_PER_DAY) / millisPerUnit;
              break;
          case Calendar.MONTH:
              result += (calendar.get(Calendar.DAY_OF_MONTH) * MILLIS_PER_DAY) / millisPerUnit;
              break;
      }
      switch (fragment) {
          // Number of days already calculated for these cases
          case Calendar.YEAR:
          case Calendar.MONTH:
          
          // The rest of the valid cases
          case Calendar.DAY_OF_YEAR:
          case Calendar.DATE:
              result += (calendar.get(Calendar.HOUR_OF_DAY) * MILLIS_PER_HOUR) / millisPerUnit;
          case Calendar.HOUR_OF_DAY:
              result += (calendar.get(Calendar.MINUTE) * MILLIS_PER_MINUTE) / millisPerUnit;
          case Calendar.MINUTE:
              result += (calendar.get(Calendar.SECOND) * MILLIS_PER_SECOND) / millisPerUnit;
          case Calendar.SECOND:
              result += (calendar.get(Calendar.MILLISECOND) * 1) / millisPerUnit;
              break;
          case Calendar.MILLISECOND: break;//never useful
              default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported");
      }
      return result;
  }
  /**
   * Returns the number of millis of a datefield, if this is a constant value
   * 
   * @param unit A Calendar field which is a valid unit for a fragment
   * @return number of millis
   * @throws IllegalArgumentException if date can"t be represented in millisenconds
   * @since 2.4 
   */
  private static long getMillisPerUnit(int unit) {
      long result = Long.MAX_VALUE;
      switch (unit) {
          case Calendar.DAY_OF_YEAR:
          case Calendar.DATE:
              result = MILLIS_PER_DAY;
              break;
          case Calendar.HOUR_OF_DAY:
              result = MILLIS_PER_HOUR;
              break;
          case Calendar.MINUTE:
              result = MILLIS_PER_MINUTE;
              break;
          case Calendar.SECOND:
              result = MILLIS_PER_SECOND;
              break;
          case Calendar.MILLISECOND:
              result = 1;
              break;
          default: throw new IllegalArgumentException("The unit " + unit + " cannot be represented is milleseconds");
      }
      return result;
  }
}





Returns the number of minutes within the fragment.

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.TimeZone;

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * A suite of utilities surrounding the use of the
 * {@link java.util.Calendar} and {@link java.util.Date} object.
 * 
 * DateUtils contains a lot of common methods considering manipulations
 * of Dates or Calendars. Some methods require some extra explanation.
 * The truncate and round methods could be considered the Math.floor(),
 * Math.ceil() or Math.round versions for dates
 * This way date-fields will be ignored in bottom-up order.
 * As a complement to these methods we"ve introduced some fragment-methods.
 * With these methods the Date-fields will be ignored in top-down order.
 * Since a date without a year is not a valid date, you have to decide in what
 * kind of date-field you want your result, for instance milliseconds or days.
 * 
 *   
 *   
 *
 * @author 
 * @author Phil Steitz
 * @author Robert Scholte
 * @since 2.0
 * @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
 */
public class Main {
  
  /**
   * The UTC time zone  (often referred to as GMT).
   */
  public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
  /**
   * Number of milliseconds in a standard second.
   * @since 2.1
   */
  public static final long MILLIS_PER_SECOND = 1000;
  /**
   * Number of milliseconds in a standard minute.
   * @since 2.1
   */
  public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
  /**
   * Number of milliseconds in a standard hour.
   * @since 2.1
   */
  public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
  /**
   * Number of milliseconds in a standard day.
   * @since 2.1
   */
  public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
  /**
   * This is half a month, so this represents whether a date is in the top
   * or bottom half of the month.
   */
  public final static int SEMI_MONTH = 1001;
  private static final int[][] fields = {
          {Calendar.MILLISECOND},
          {Calendar.SECOND},
          {Calendar.MINUTE},
          {Calendar.HOUR_OF_DAY, Calendar.HOUR},
          {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM 
              /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
          },
          {Calendar.MONTH, DateUtils.SEMI_MONTH},
          {Calendar.YEAR},
          {Calendar.ERA}};
  /**
   * A week range, starting on Sunday.
   */
  public final static int RANGE_WEEK_SUNDAY = 1;
  /**
   * A week range, starting on Monday.
   */
  public final static int RANGE_WEEK_MONDAY = 2;
  /**
   * A week range, starting on the day focused.
   */
  public final static int RANGE_WEEK_RELATIVE = 3;
  /**
   * A week range, centered around the day focused.
   */
  public final static int RANGE_WEEK_CENTER = 4;
  /**
   * A month range, the week starting on Sunday.
   */
  public final static int RANGE_MONTH_SUNDAY = 5;
  /**
   * A month range, the week starting on Monday.
   */
  public final static int RANGE_MONTH_MONDAY = 6;
  
  
  /**
   * Returns the number of minutes within the 
   * fragment. All datefields greater than the fragment will be ignored. 
   * 
   * Asking the minutes of any date will only return the number of minutes
   * of the current hour (resulting in a number between 0 and 59). This 
   * method will retrieve the number of minutes for any fragment. 
   * For example, if you want to calculate the number of minutes past this month, 
   * your fragment is Calendar.MONTH. The result will be all minutes of the 
   * past day(s) and hour(s). 
   * 
   * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both 
   * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, 
   * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND
   * A fragment less than or equal to a MINUTE field will return 0. 
   * 
   * 
   * <ul>
   *  <li>January 1, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will return 15
   *   (equivalent to calendar.get(Calendar.MINUTES))</li>
   *  <li>January 6, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will return 15
   *   (equivalent to calendar.get(Calendar.MINUTES))</li>
   *  <li>January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 15</li>
   *  <li>January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 435 (7*60 + 15)</li>
   *  <li>January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0
   *   (a millisecond cannot be split in minutes)</li>
   * </ul>
   * 
   * 
   * @param calendar the calendar to work with, not null
   * @param fragment the Calendar field part of calendar to calculate 
   * @return number of minutes within the fragment of date
   * @throws IllegalArgumentException if the date is <code>null</code> or 
   * fragment is not supported
   * @since 2.4
   */
  public static long getFragmentInMinutes(Calendar calendar, int fragment) {
      return getFragment(calendar, fragment, Calendar.MINUTE);
  }
  
  /**
   * Date-version for fragment-calculation in any unit
   * 
   * @param date the date to work with, not null
   * @param fragment the Calendar field part of date to calculate 
   * @param unit Calendar field defining the unit
   * @return number of units within the fragment of the date
   * @throws IllegalArgumentException if the date is <code>null</code> or 
   * fragment is not supported
   * @since 2.4
   */
  private static long getFragment(Date date, int fragment, int unit) {
      if(date == null) {
          throw  new IllegalArgumentException("The date must not be null");
      }
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(date);
      return getFragment(calendar, fragment, unit);
  }
  /**
   * Calendar-version for fragment-calculation in any unit
   * 
   * @param calendar the calendar to work with, not null
   * @param fragment the Calendar field part of calendar to calculate 
   * @param unit Calendar field defining the unit
   * @return number of units within the fragment of the calendar
   * @throws IllegalArgumentException if the date is <code>null</code> or 
   * fragment is not supported
   * @since 2.4
   */
  private static long getFragment(Calendar calendar, int fragment, int unit) {
      if(calendar == null) {
          throw  new IllegalArgumentException("The date must not be null"); 
      }
      long millisPerUnit = getMillisPerUnit(unit);
      long result = 0;
      
      // Fragments bigger than a day require a breakdown to days
      switch (fragment) {
          case Calendar.YEAR:
              result += (calendar.get(Calendar.DAY_OF_YEAR) * MILLIS_PER_DAY) / millisPerUnit;
              break;
          case Calendar.MONTH:
              result += (calendar.get(Calendar.DAY_OF_MONTH) * MILLIS_PER_DAY) / millisPerUnit;
              break;
      }
      switch (fragment) {
          // Number of days already calculated for these cases
          case Calendar.YEAR:
          case Calendar.MONTH:
          
          // The rest of the valid cases
          case Calendar.DAY_OF_YEAR:
          case Calendar.DATE:
              result += (calendar.get(Calendar.HOUR_OF_DAY) * MILLIS_PER_HOUR) / millisPerUnit;
          case Calendar.HOUR_OF_DAY:
              result += (calendar.get(Calendar.MINUTE) * MILLIS_PER_MINUTE) / millisPerUnit;
          case Calendar.MINUTE:
              result += (calendar.get(Calendar.SECOND) * MILLIS_PER_SECOND) / millisPerUnit;
          case Calendar.SECOND:
              result += (calendar.get(Calendar.MILLISECOND) * 1) / millisPerUnit;
              break;
          case Calendar.MILLISECOND: break;//never useful
              default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported");
      }
      return result;
  }
  /**
   * Returns the number of millis of a datefield, if this is a constant value
   * 
   * @param unit A Calendar field which is a valid unit for a fragment
   * @return number of millis
   * @throws IllegalArgumentException if date can"t be represented in millisenconds
   * @since 2.4 
   */
  private static long getMillisPerUnit(int unit) {
      long result = Long.MAX_VALUE;
      switch (unit) {
          case Calendar.DAY_OF_YEAR:
          case Calendar.DATE:
              result = MILLIS_PER_DAY;
              break;
          case Calendar.HOUR_OF_DAY:
              result = MILLIS_PER_HOUR;
              break;
          case Calendar.MINUTE:
              result = MILLIS_PER_MINUTE;
              break;
          case Calendar.SECOND:
              result = MILLIS_PER_SECOND;
              break;
          case Calendar.MILLISECOND:
              result = 1;
              break;
          default: throw new IllegalArgumentException("The unit " + unit + " cannot be represented is milleseconds");
      }
      return result;
  }
}





Returns the number of seconds within the fragment.

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.TimeZone;

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * A suite of utilities surrounding the use of the
 * {@link java.util.Calendar} and {@link java.util.Date} object.
 * 
 * DateUtils contains a lot of common methods considering manipulations
 * of Dates or Calendars. Some methods require some extra explanation.
 * The truncate and round methods could be considered the Math.floor(),
 * Math.ceil() or Math.round versions for dates
 * This way date-fields will be ignored in bottom-up order.
 * As a complement to these methods we"ve introduced some fragment-methods.
 * With these methods the Date-fields will be ignored in top-down order.
 * Since a date without a year is not a valid date, you have to decide in what
 * kind of date-field you want your result, for instance milliseconds or days.
 * 
 *   
 *   
 *
 * @author 
 * @author Phil Steitz
 * @author Robert Scholte
 * @since 2.0
 * @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
 */
public class Main {
  
  /**
   * The UTC time zone  (often referred to as GMT).
   */
  public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
  /**
   * Number of milliseconds in a standard second.
   * @since 2.1
   */
  public static final long MILLIS_PER_SECOND = 1000;
  /**
   * Number of milliseconds in a standard minute.
   * @since 2.1
   */
  public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
  /**
   * Number of milliseconds in a standard hour.
   * @since 2.1
   */
  public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
  /**
   * Number of milliseconds in a standard day.
   * @since 2.1
   */
  public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
  /**
   * This is half a month, so this represents whether a date is in the top
   * or bottom half of the month.
   */
  public final static int SEMI_MONTH = 1001;
  private static final int[][] fields = {
          {Calendar.MILLISECOND},
          {Calendar.SECOND},
          {Calendar.MINUTE},
          {Calendar.HOUR_OF_DAY, Calendar.HOUR},
          {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM 
              /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
          },
          {Calendar.MONTH, DateUtils.SEMI_MONTH},
          {Calendar.YEAR},
          {Calendar.ERA}};
  /**
   * A week range, starting on Sunday.
   */
  public final static int RANGE_WEEK_SUNDAY = 1;
  /**
   * A week range, starting on Monday.
   */
  public final static int RANGE_WEEK_MONDAY = 2;
  /**
   * A week range, starting on the day focused.
   */
  public final static int RANGE_WEEK_RELATIVE = 3;
  /**
   * A week range, centered around the day focused.
   */
  public final static int RANGE_WEEK_CENTER = 4;
  /**
   * A month range, the week starting on Sunday.
   */
  public final static int RANGE_MONTH_SUNDAY = 5;
  /**
   * A month range, the week starting on Monday.
   */
  public final static int RANGE_MONTH_MONDAY = 6;
  
  
  
  /**
   * Returns the number of seconds within the 
   * fragment. All datefields greater than the fragment will be ignored. 
   * 
   * Asking the seconds of any date will only return the number of seconds
   * of the current minute (resulting in a number between 0 and 59). This 
   * method will retrieve the number of seconds for any fragment. 
   * For example, if you want to calculate the number of seconds past today, 
   * your fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will
   * be all seconds of the past hour(s) and minutes(s). 
   * 
   * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both 
   * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, 
   * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND
   * A fragment less than or equal to a SECOND field will return 0. 
   * 
   * 
   * <ul>
   *  <li>January 1, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10
   *   (equivalent to deprecated date.getSeconds())</li>
   *  <li>January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10
   *   (equivalent to deprecated date.getSeconds())</li>
   *  <li>January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 26110
   *   (7*3600 + 15*60 + 10)</li>
   *  <li>January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0
   *   (a millisecond cannot be split in seconds)</li>
   * </ul>
   * 
   * 
   * @param date the date to work with, not null
   * @param fragment the Calendar field part of date to calculate 
   * @return number of seconds within the fragment of date
   * @throws IllegalArgumentException if the date is <code>null</code> or
   * fragment is not supported
   * @since 2.4
   */
  public static long getFragmentInSeconds(Date date, int fragment) {
      return getFragment(date, fragment, Calendar.SECOND);
  }
  
  
  /**
   * Date-version for fragment-calculation in any unit
   * 
   * @param date the date to work with, not null
   * @param fragment the Calendar field part of date to calculate 
   * @param unit Calendar field defining the unit
   * @return number of units within the fragment of the date
   * @throws IllegalArgumentException if the date is <code>null</code> or 
   * fragment is not supported
   * @since 2.4
   */
  private static long getFragment(Date date, int fragment, int unit) {
      if(date == null) {
          throw  new IllegalArgumentException("The date must not be null");
      }
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(date);
      return getFragment(calendar, fragment, unit);
  }
  /**
   * Calendar-version for fragment-calculation in any unit
   * 
   * @param calendar the calendar to work with, not null
   * @param fragment the Calendar field part of calendar to calculate 
   * @param unit Calendar field defining the unit
   * @return number of units within the fragment of the calendar
   * @throws IllegalArgumentException if the date is <code>null</code> or 
   * fragment is not supported
   * @since 2.4
   */
  private static long getFragment(Calendar calendar, int fragment, int unit) {
      if(calendar == null) {
          throw  new IllegalArgumentException("The date must not be null"); 
      }
      long millisPerUnit = getMillisPerUnit(unit);
      long result = 0;
      
      // Fragments bigger than a day require a breakdown to days
      switch (fragment) {
          case Calendar.YEAR:
              result += (calendar.get(Calendar.DAY_OF_YEAR) * MILLIS_PER_DAY) / millisPerUnit;
              break;
          case Calendar.MONTH:
              result += (calendar.get(Calendar.DAY_OF_MONTH) * MILLIS_PER_DAY) / millisPerUnit;
              break;
      }
      switch (fragment) {
          // Number of days already calculated for these cases
          case Calendar.YEAR:
          case Calendar.MONTH:
          
          // The rest of the valid cases
          case Calendar.DAY_OF_YEAR:
          case Calendar.DATE:
              result += (calendar.get(Calendar.HOUR_OF_DAY) * MILLIS_PER_HOUR) / millisPerUnit;
          case Calendar.HOUR_OF_DAY:
              result += (calendar.get(Calendar.MINUTE) * MILLIS_PER_MINUTE) / millisPerUnit;
          case Calendar.MINUTE:
              result += (calendar.get(Calendar.SECOND) * MILLIS_PER_SECOND) / millisPerUnit;
          case Calendar.SECOND:
              result += (calendar.get(Calendar.MILLISECOND) * 1) / millisPerUnit;
              break;
          case Calendar.MILLISECOND: break;//never useful
              default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported");
      }
      return result;
  }
  /**
   * Returns the number of millis of a datefield, if this is a constant value
   * 
   * @param unit A Calendar field which is a valid unit for a fragment
   * @return number of millis
   * @throws IllegalArgumentException if date can"t be represented in millisenconds
   * @since 2.4 
   */
  private static long getMillisPerUnit(int unit) {
      long result = Long.MAX_VALUE;
      switch (unit) {
          case Calendar.DAY_OF_YEAR:
          case Calendar.DATE:
              result = MILLIS_PER_DAY;
              break;
          case Calendar.HOUR_OF_DAY:
              result = MILLIS_PER_HOUR;
              break;
          case Calendar.MINUTE:
              result = MILLIS_PER_MINUTE;
              break;
          case Calendar.SECOND:
              result = MILLIS_PER_SECOND;
              break;
          case Calendar.MILLISECOND:
              result = 1;
              break;
          default: throw new IllegalArgumentException("The unit " + unit + " cannot be represented is milleseconds");
      }
      return result;
  }
}





Returns true if endDate is after startDate or if startDate equals endDate.

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  The ASF licenses this file to You
 * under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.  For additional information regarding
 * copyright in this work, please see the NOTICE file in the top level
 * directory of this distribution.
 */
import java.util.Date;
public class Utils {
  /**
   * Returns true if endDate is after startDate or if startDate equals endDate.
   * Returns false if either value is null.  If equalOK, returns true if the
   * dates are equal.
   **/
  public static boolean isValidDateRange(Date startDate, Date endDate, boolean equalOK) {
      // false if either value is null
      if (startDate == null || endDate == null) { return false; }
      
      if (equalOK) {
          // true if they are equal
          if (startDate.equals(endDate)) { return true; }
      }
      
      // true if endDate after startDate
      if (endDate.after(startDate)) { return true; }
      
      return false;
  }
}





Round this date, leaving the field specified as the most significant field.

import java.util.Calendar;
import java.util.Date;
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * A suite of utilities surrounding the use of the
 * {@link java.util.Calendar} and {@link java.util.Date} object.
 * 
 * DateUtils contains a lot of common methods considering manipulations
 * of Dates or Calendars. Some methods require some extra explanation.
 * The truncate and round methods could be considered the Math.floor(),
 * Math.ceil() or Math.round versions for dates
 * This way date-fields will be ignored in bottom-up order.
 * As a complement to these methods we"ve introduced some fragment-methods.
 * With these methods the Date-fields will be ignored in top-down order.
 * Since a date without a year is not a valid date, you have to decide in what
 * kind of date-field you want your result, for instance milliseconds or days.
 * 
 *   
 *   
 *
 * @author 
 * @author Phil Steitz
 * @author Robert Scholte
 * @since 2.0
 * @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
 */
public class Main {
  private static final int[][] fields = {
    {Calendar.MILLISECOND},
    {Calendar.SECOND},
    {Calendar.MINUTE},
    {Calendar.HOUR_OF_DAY, Calendar.HOUR},
    {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM 
        /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
    },
    {Calendar.MONTH, DateUtils.SEMI_MONTH},
    {Calendar.YEAR},
    {Calendar.ERA}};
  /**
   * Round this date, leaving the field specified as the most
   * significant field.
   *
   * For example, if you had the datetime of 28 Mar 2002
   * 13:45:01.231, if this was passed with HOUR, it would return
   * 28 Mar 2002 14:00:00.000. If this was passed with MONTH, it
   * would return 1 April 2002 0:00:00.000.
   * 
   * For a date in a timezone that handles the change to daylight
   * saving time, rounding to Calendar.HOUR_OF_DAY will behave as follows.
   * Suppose daylight saving time begins at 02:00 on March 30. Rounding a 
   * date that crosses this time would produce the following values:
   * <ul>
   * <li>March 30, 2003 01:10 rounds to March 30, 2003 01:00</li>
   * <li>March 30, 2003 01:40 rounds to March 30, 2003 03:00</li>
   * <li>March 30, 2003 02:10 rounds to March 30, 2003 03:00</li>
   * <li>March 30, 2003 02:40 rounds to March 30, 2003 04:00</li>
   * </ul>
   * 
   * 
   * @param date  the date to work with
   * @param field  the field from <code>Calendar</code>
   *  or <code>SEMI_MONTH</code>
   * @return the rounded date (a different object)
   * @throws IllegalArgumentException if the date is <code>null</code>
   * @throws ArithmeticException if the year is over 280 million
   */
  public static Calendar round(Calendar date, int field) {
      if (date == null) {
          throw new IllegalArgumentException("The date must not be null");
      }
      Calendar rounded = (Calendar) date.clone();
      modify(rounded, field, true);
      return rounded;
  }
  //-----------------------------------------------------------------------
  /**
   * Internal calculation method.
   * 
   * @param val  the calendar
   * @param field  the field constant
   * @param round  true to round, false to truncate
   * @throws ArithmeticException if the year is over 280 million
   */
  private static void modify(Calendar val, int field, boolean round) {
      if (val.get(Calendar.YEAR) > 280000000) {
          throw new ArithmeticException("Calendar value too large for accurate calculations");
      }
      
      if (field == Calendar.MILLISECOND) {
          return;
      }
      // ----------------- Fix for LANG-59 ---------------------- START ---------------
      // see http://issues.apache.org/jira/browse/LANG-59
      //
      // Manually truncate milliseconds, seconds and minutes, rather than using
      // Calendar methods.
      Date date = val.getTime();
      long time = date.getTime();
      boolean done = false;
      // truncate milliseconds
      int millisecs = val.get(Calendar.MILLISECOND);
      if (!round || millisecs < 500) {
          time = time - millisecs;
      }
      if (field == Calendar.SECOND) {
          done = true;
      }
      // truncate seconds
      int seconds = val.get(Calendar.SECOND);
      if (!done && (!round || seconds < 30)) {
          time = time - (seconds * 1000L);
      }
      if (field == Calendar.MINUTE) {
          done = true;
      }
      // truncate minutes
      int minutes = val.get(Calendar.MINUTE);
      if (!done && (!round || minutes < 30)) {
          time = time - (minutes * 60000L);
      }
      // reset time
      if (date.getTime() != time) {
          date.setTime(time);
          val.setTime(date);
      }
      // ----------------- Fix for LANG-59 ----------------------- END ----------------
      boolean roundUp = false;
      for (int i = 0; i < fields.length; i++) {
          for (int j = 0; j < fields[i].length; j++) {
              if (fields[i][j] == field) {
                  //This is our field... we stop looping
                  if (round && roundUp) {
                      if (field == DateUtils.SEMI_MONTH) {
                          //This is a special case that"s hard to generalize
                          //If the date is 1, we round up to 16, otherwise
                          //  we subtract 15 days and add 1 month
                          if (val.get(Calendar.DATE) == 1) {
                              val.add(Calendar.DATE, 15);
                          } else {
                              val.add(Calendar.DATE, -15);
                              val.add(Calendar.MONTH, 1);
                          }
                      } else {
                          //We need at add one to this field since the
                          //  last number causes us to round up
                          val.add(fields[i][0], 1);
                      }
                  }
                  return;
              }
          }
          //We have various fields that are not easy roundings
          int offset = 0;
          boolean offsetSet = false;
          //These are special types of fields that require different rounding rules
          switch (field) {
              case DateUtils.SEMI_MONTH:
                  if (fields[i][0] == Calendar.DATE) {
                      //If we"re going to drop the DATE field"s value,
                      //  we want to do this our own way.
                      //We need to subtrace 1 since the date has a minimum of 1
                      offset = val.get(Calendar.DATE) - 1;
                      //If we"re above 15 days adjustment, that means we"re in the
                      //  bottom half of the month and should stay accordingly.
                      if (offset >= 15) {
                          offset -= 15;
                      }
                      //Record whether we"re in the top or bottom half of that range
                      roundUp = offset > 7;
                      offsetSet = true;
                  }
                  break;
              case Calendar.AM_PM:
                  if (fields[i][0] == Calendar.HOUR_OF_DAY) {
                      //If we"re going to drop the HOUR field"s value,
                      //  we want to do this our own way.
                      offset = val.get(Calendar.HOUR_OF_DAY);
                      if (offset >= 12) {
                          offset -= 12;
                      }
                      roundUp = offset > 6;
                      offsetSet = true;
                  }
                  break;
          }
          if (!offsetSet) {
              int min = val.getActualMinimum(fields[i][0]);
              int max = val.getActualMaximum(fields[i][0]);
              //Calculate the offset from the minimum allowed value
              offset = val.get(fields[i][0]) - min;
              //Set roundUp if this is more than half way between the minimum and maximum
              roundUp = offset > ((max - min) / 2);
          }
          //We need to remove this field
          if (offset != 0) {
              val.set(fields[i][0], val.get(fields[i][0]) - offset);
          }
      }
      throw new IllegalArgumentException("The field " + field + " is not supported");
  }
}





Substract 1 year from the calendar

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar cal = Calendar.getInstance();
    System.out.println("Today : " + cal.getTime());
    // Substract 1 year from the calendar
    cal.add(Calendar.YEAR, -1);
    System.out.println("1 year ago: " + cal.getTime());
  }
}





Substract 30 days from the calendar

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar cal = Calendar.getInstance();
    System.out.println("Today : " + cal.getTime());
    // Substract 30 days from the calendar
    cal.add(Calendar.DATE, -30);
    System.out.println("30 days ago: " + cal.getTime());
  }
}





Substract days from current date using Calendar.add method

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
    now = Calendar.getInstance();
    now.add(Calendar.DATE, -10);
    System.out.println("date before 10 days : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
  }
}
/*
Current date : 2-20-2009
date before 10 days : 2-10-2009
*/





Substract hours from current date using Calendar.add method

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current Date : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
    System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":"
        + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
    now = Calendar.getInstance();
    now.add(Calendar.HOUR, -3);
    System.out.println("Time before 3 hours : " + now.get(Calendar.HOUR_OF_DAY) + ":"
        + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
  }
}





Substract minutes from current date using Calendar.add method

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":"
        + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
    now = Calendar.getInstance();
    now.add(Calendar.MINUTE, -50);
    System.out.println("Time before 50 minutes : " + now.get(Calendar.HOUR_OF_DAY) + ":"
        + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
  }
}





Substract months from current date using Calendar.add method

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
    now = Calendar.getInstance();
    now.add(Calendar.MONTH, -5);
    System.out.println("date before 5 months : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
  }
}





Substract seconds from current time using Calendar.add method

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":"
        + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
    now = Calendar.getInstance();
    now.add(Calendar.SECOND, -50);
    System.out.println("Time before 50 minutes : " + now.get(Calendar.HOUR_OF_DAY) + ":"
        + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));  }
}





Substract week from current date

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
    System.out.println("Current week of month is : " + now.get(Calendar.WEEK_OF_MONTH));
    System.out.println("Current week of year is : " + now.get(Calendar.WEEK_OF_YEAR));
    now = Calendar.getInstance();
    now.add(Calendar.WEEK_OF_YEAR, -50);
    System.out.println("date before 50 weeks : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
  }
}





Substract year from current date

import java.util.Calendar;
public class Main {
  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
    now = Calendar.getInstance();
    now.add(Calendar.YEAR, -100);
    System.out.println("date before 100 years : " + (now.get(Calendar.MONTH) + 1) + "-"
        + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
  }
}





subtract 4 hours from the time and print out the date and time

import java.text.DateFormat;
import java.util.Calendar;
public class CalendarManipulation {
  public static void main(String s[]) {
    Calendar cal = Calendar.getInstance();
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL,
        DateFormat.MEDIUM);
    System.out.println(df.format(cal.getTime()));
    cal.add(Calendar.HOUR, -4);
    System.out.println(df.format(cal.getTime()));
  }
}





Truncate this date(Calendar), leaving the field specified as the most significant field.

import java.util.Calendar;
import java.util.Date;
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * A suite of utilities surrounding the use of the
 * {@link java.util.Calendar} and {@link java.util.Date} object.
 * 
 * DateUtils contains a lot of common methods considering manipulations
 * of Dates or Calendars. Some methods require some extra explanation.
 * The truncate and round methods could be considered the Math.floor(),
 * Math.ceil() or Math.round versions for dates
 * This way date-fields will be ignored in bottom-up order.
 * As a complement to these methods we"ve introduced some fragment-methods.
 * With these methods the Date-fields will be ignored in top-down order.
 * Since a date without a year is not a valid date, you have to decide in what
 * kind of date-field you want your result, for instance milliseconds or days.
 * 
 *   
 *   
 *
 * @author 
 * @author Phil Steitz
 * @author Robert Scholte
 * @since 2.0
 * @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
 */
public class Main {
  private static final int[][] fields = {
    {Calendar.MILLISECOND},
    {Calendar.SECOND},
    {Calendar.MINUTE},
    {Calendar.HOUR_OF_DAY, Calendar.HOUR},
    {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM 
        /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
    },
    {Calendar.MONTH, DateUtils.SEMI_MONTH},
    {Calendar.YEAR},
    {Calendar.ERA}};

  /**
   * Truncate this date, leaving the field specified as the most
   * significant field.
   *
   * For example, if you had the datetime of 28 Mar 2002
   * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
   * 2002 13:00:00.000.  If this was passed with MONTH, it would
   * return 1 Mar 2002 0:00:00.000.
   * 
   * @param date  the date to work with
   * @param field  the field from <code>Calendar</code>
   *  or <code>SEMI_MONTH</code>
   * @return the rounded date (a different object)
   * @throws IllegalArgumentException if the date is <code>null</code>
   * @throws ArithmeticException if the year is over 280 million
   */
  public static Calendar truncate(Calendar date, int field) {
      if (date == null) {
          throw new IllegalArgumentException("The date must not be null");
      }
      Calendar truncated = (Calendar) date.clone();
      modify(truncated, field, false);
      return truncated;
  }
  //-----------------------------------------------------------------------
  /**
   * Internal calculation method.
   * 
   * @param val  the calendar
   * @param field  the field constant
   * @param round  true to round, false to truncate
   * @throws ArithmeticException if the year is over 280 million
   */
  private static void modify(Calendar val, int field, boolean round) {
      if (val.get(Calendar.YEAR) > 280000000) {
          throw new ArithmeticException("Calendar value too large for accurate calculations");
      }
      
      if (field == Calendar.MILLISECOND) {
          return;
      }
      // ----------------- Fix for LANG-59 ---------------------- START ---------------
      // see http://issues.apache.org/jira/browse/LANG-59
      //
      // Manually truncate milliseconds, seconds and minutes, rather than using
      // Calendar methods.
      Date date = val.getTime();
      long time = date.getTime();
      boolean done = false;
      // truncate milliseconds
      int millisecs = val.get(Calendar.MILLISECOND);
      if (!round || millisecs < 500) {
          time = time - millisecs;
      }
      if (field == Calendar.SECOND) {
          done = true;
      }
      // truncate seconds
      int seconds = val.get(Calendar.SECOND);
      if (!done && (!round || seconds < 30)) {
          time = time - (seconds * 1000L);
      }
      if (field == Calendar.MINUTE) {
          done = true;
      }
      // truncate minutes
      int minutes = val.get(Calendar.MINUTE);
      if (!done && (!round || minutes < 30)) {
          time = time - (minutes * 60000L);
      }
      // reset time
      if (date.getTime() != time) {
          date.setTime(time);
          val.setTime(date);
      }
      // ----------------- Fix for LANG-59 ----------------------- END ----------------
      boolean roundUp = false;
      for (int i = 0; i < fields.length; i++) {
          for (int j = 0; j < fields[i].length; j++) {
              if (fields[i][j] == field) {
                  //This is our field... we stop looping
                  if (round && roundUp) {
                      if (field == DateUtils.SEMI_MONTH) {
                          //This is a special case that"s hard to generalize
                          //If the date is 1, we round up to 16, otherwise
                          //  we subtract 15 days and add 1 month
                          if (val.get(Calendar.DATE) == 1) {
                              val.add(Calendar.DATE, 15);
                          } else {
                              val.add(Calendar.DATE, -15);
                              val.add(Calendar.MONTH, 1);
                          }
                      } else {
                          //We need at add one to this field since the
                          //  last number causes us to round up
                          val.add(fields[i][0], 1);
                      }
                  }
                  return;
              }
          }
          //We have various fields that are not easy roundings
          int offset = 0;
          boolean offsetSet = false;
          //These are special types of fields that require different rounding rules
          switch (field) {
              case DateUtils.SEMI_MONTH:
                  if (fields[i][0] == Calendar.DATE) {
                      //If we"re going to drop the DATE field"s value,
                      //  we want to do this our own way.
                      //We need to subtrace 1 since the date has a minimum of 1
                      offset = val.get(Calendar.DATE) - 1;
                      //If we"re above 15 days adjustment, that means we"re in the
                      //  bottom half of the month and should stay accordingly.
                      if (offset >= 15) {
                          offset -= 15;
                      }
                      //Record whether we"re in the top or bottom half of that range
                      roundUp = offset > 7;
                      offsetSet = true;
                  }
                  break;
              case Calendar.AM_PM:
                  if (fields[i][0] == Calendar.HOUR_OF_DAY) {
                      //If we"re going to drop the HOUR field"s value,
                      //  we want to do this our own way.
                      offset = val.get(Calendar.HOUR_OF_DAY);
                      if (offset >= 12) {
                          offset -= 12;
                      }
                      roundUp = offset > 6;
                      offsetSet = true;
                  }
                  break;
          }
          if (!offsetSet) {
              int min = val.getActualMinimum(fields[i][0]);
              int max = val.getActualMaximum(fields[i][0]);
              //Calculate the offset from the minimum allowed value
              offset = val.get(fields[i][0]) - min;
              //Set roundUp if this is more than half way between the minimum and maximum
              roundUp = offset > ((max - min) / 2);
          }
          //We need to remove this field
          if (offset != 0) {
              val.set(fields[i][0], val.get(fields[i][0]) - offset);
          }
      }
      throw new IllegalArgumentException("The field " + field + " is not supported");
  }
}





Truncate this date, leaving the field specified as the most significant field.

import java.util.Calendar;
import java.util.Date;
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * A suite of utilities surrounding the use of the
 * {@link java.util.Calendar} and {@link java.util.Date} object.
 * 
 * DateUtils contains a lot of common methods considering manipulations
 * of Dates or Calendars. Some methods require some extra explanation.
 * The truncate and round methods could be considered the Math.floor(),
 * Math.ceil() or Math.round versions for dates
 * This way date-fields will be ignored in bottom-up order.
 * As a complement to these methods we"ve introduced some fragment-methods.
 * With these methods the Date-fields will be ignored in top-down order.
 * Since a date without a year is not a valid date, you have to decide in what
 * kind of date-field you want your result, for instance milliseconds or days.
 * 
 *   
 *   
 *
 * @author 
 * @author Phil Steitz
 * @author Robert Scholte
 * @since 2.0
 * @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
 */
public class Main {
  private static final int[][] fields = {
    {Calendar.MILLISECOND},
    {Calendar.SECOND},
    {Calendar.MINUTE},
    {Calendar.HOUR_OF_DAY, Calendar.HOUR},
    {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM 
        /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
    },
    {Calendar.MONTH, DateUtils.SEMI_MONTH},
    {Calendar.YEAR},
    {Calendar.ERA}};

  //-----------------------------------------------------------------------
  /**
   * Truncate this date, leaving the field specified as the most
   * significant field.
   *
   * For example, if you had the datetime of 28 Mar 2002
   * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
   * 2002 13:00:00.000.  If this was passed with MONTH, it would
   * return 1 Mar 2002 0:00:00.000.s
   * 
   * @param date  the date to work with
   * @param field  the field from <code>Calendar</code>
   *  or <code>SEMI_MONTH</code>
   * @return the rounded date
   * @throws IllegalArgumentException if the date is <code>null</code>
   * @throws ArithmeticException if the year is over 280 million
   */
  public static Date truncate(Date date, int field) {
      if (date == null) {
          throw new IllegalArgumentException("The date must not be null");
      }
      Calendar gval = Calendar.getInstance();
      gval.setTime(date);
      modify(gval, field, false);
      return gval.getTime();
  }
  //-----------------------------------------------------------------------
  /**
   * Internal calculation method.
   * 
   * @param val  the calendar
   * @param field  the field constant
   * @param round  true to round, false to truncate
   * @throws ArithmeticException if the year is over 280 million
   */
  private static void modify(Calendar val, int field, boolean round) {
      if (val.get(Calendar.YEAR) > 280000000) {
          throw new ArithmeticException("Calendar value too large for accurate calculations");
      }
      
      if (field == Calendar.MILLISECOND) {
          return;
      }
      // ----------------- Fix for LANG-59 ---------------------- START ---------------
      // see http://issues.apache.org/jira/browse/LANG-59
      //
      // Manually truncate milliseconds, seconds and minutes, rather than using
      // Calendar methods.
      Date date = val.getTime();
      long time = date.getTime();
      boolean done = false;
      // truncate milliseconds
      int millisecs = val.get(Calendar.MILLISECOND);
      if (!round || millisecs < 500) {
          time = time - millisecs;
      }
      if (field == Calendar.SECOND) {
          done = true;
      }
      // truncate seconds
      int seconds = val.get(Calendar.SECOND);
      if (!done && (!round || seconds < 30)) {
          time = time - (seconds * 1000L);
      }
      if (field == Calendar.MINUTE) {
          done = true;
      }
      // truncate minutes
      int minutes = val.get(Calendar.MINUTE);
      if (!done && (!round || minutes < 30)) {
          time = time - (minutes * 60000L);
      }
      // reset time
      if (date.getTime() != time) {
          date.setTime(time);
          val.setTime(date);
      }
      // ----------------- Fix for LANG-59 ----------------------- END ----------------
      boolean roundUp = false;
      for (int i = 0; i < fields.length; i++) {
          for (int j = 0; j < fields[i].length; j++) {
              if (fields[i][j] == field) {
                  //This is our field... we stop looping
                  if (round && roundUp) {
                      if (field == DateUtils.SEMI_MONTH) {
                          //This is a special case that"s hard to generalize
                          //If the date is 1, we round up to 16, otherwise
                          //  we subtract 15 days and add 1 month
                          if (val.get(Calendar.DATE) == 1) {
                              val.add(Calendar.DATE, 15);
                          } else {
                              val.add(Calendar.DATE, -15);
                              val.add(Calendar.MONTH, 1);
                          }
                      } else {
                          //We need at add one to this field since the
                          //  last number causes us to round up
                          val.add(fields[i][0], 1);
                      }
                  }
                  return;
              }
          }
          //We have various fields that are not easy roundings
          int offset = 0;
          boolean offsetSet = false;
          //These are special types of fields that require different rounding rules
          switch (field) {
              case DateUtils.SEMI_MONTH:
                  if (fields[i][0] == Calendar.DATE) {
                      //If we"re going to drop the DATE field"s value,
                      //  we want to do this our own way.
                      //We need to subtrace 1 since the date has a minimum of 1
                      offset = val.get(Calendar.DATE) - 1;
                      //If we"re above 15 days adjustment, that means we"re in the
                      //  bottom half of the month and should stay accordingly.
                      if (offset >= 15) {
                          offset -= 15;
                      }
                      //Record whether we"re in the top or bottom half of that range
                      roundUp = offset > 7;
                      offsetSet = true;
                  }
                  break;
              case Calendar.AM_PM:
                  if (fields[i][0] == Calendar.HOUR_OF_DAY) {
                      //If we"re going to drop the HOUR field"s value,
                      //  we want to do this our own way.
                      offset = val.get(Calendar.HOUR_OF_DAY);
                      if (offset >= 12) {
                          offset -= 12;
                      }
                      roundUp = offset > 6;
                      offsetSet = true;
                  }
                  break;
          }
          if (!offsetSet) {
              int min = val.getActualMinimum(fields[i][0]);
              int max = val.getActualMaximum(fields[i][0]);
              //Calculate the offset from the minimum allowed value
              offset = val.get(fields[i][0]) - min;
              //Set roundUp if this is more than half way between the minimum and maximum
              roundUp = offset > ((max - min) / 2);
          }
          //We need to remove this field
          if (offset != 0) {
              val.set(fields[i][0], val.get(fields[i][0]) - offset);
          }
      }
      throw new IllegalArgumentException("The field " + field + " is not supported");
  }
}