Java Month Add getEndOfMonth(long date)

Here you can find the source of getEndOfMonth(long date)

Description

Returns the date corresponding to the end of the month.

License

Open Source License

Parameter

Parameter Description
date Base date

Return

End of month.

Declaration

public static long getEndOfMonth(long date) 

Method Source Code

//package com.java2s;
/*/*from w w w  .  j  a v  a  2s  . c o  m*/
 * $Id: DateUtils.java,v 1.1 2004/08/12 00:24:33 dmouse Exp $
 *
 * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

import java.util.*;

public class Main {
    private static Calendar CALENDAR = Calendar.getInstance();

    /**
     * Returns the date corresponding to the end of the month.
     *
     * @param date Base date
     * @return End of month.
     */
    public static long getEndOfMonth(long date) {
        return getMonth(date, 1);
    }

    private static long getMonth(long date, int increment) {
        Calendar calendar = CALENDAR;
        synchronized (calendar) {
            calendar.setTimeInMillis(date);
            if (increment == -1) {
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                return startOfDayInMillis(calendar.getTimeInMillis());
            } else {
                calendar.add(Calendar.MONTH, 1);
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.add(Calendar.MILLISECOND, -1);
                return calendar.getTimeInMillis();
            }
        }
    }

    /**
    * Returns day in millis with the hours, milliseconds, seconds and minutes
    * set to 0.
    *
    * @param date long used in calculating start of day
    * @return Start of <code>date</code>
    */
    public static long startOfDayInMillis(long date) {
        Calendar calendar = CALENDAR;
        synchronized (calendar) {
            calendar.setTimeInMillis(date);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MINUTE, 0);
            return calendar.getTimeInMillis();
        }
    }
}

Related

  1. addMonths2(String dateStr, int months)
  2. addMonthsAndDays(Date date, int months, int days)
  3. addMonthTimetamp(long lTimeStamp, String _pattern, int month)
  4. getEndOfMonth(Date currentDate)
  5. getEndOfMonth(Date date)
  6. monthAdd(final String strDate, final int month)