Java Day End endOfDay(Date dt)

Here you can find the source of endOfDay(Date dt)

Description

Returns a new date at the end of the day of the original date.

License

Apache License

Parameter

Parameter Description
dt The date to find the end of day for.

Return

A new date representing the end of the day.

Declaration

public static Date endOfDay(Date dt) 

Method Source Code


//package com.java2s;
/*//from   w  w w . ja  v  a  2 s . c  om
 *  Copyright 2006 The National Library of New Zealand
 *
 *  Licensed 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.
 */

import java.util.Calendar;
import java.util.Date;

public class Main {
    /**
     * Returns a new date at the end of the day of the original
     * date.
     * @param dt The date to find the end of day for.
     * @return A new date representing the end of the day.
     */
    public static Date endOfDay(Date dt) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        clearTime(cal);

        cal.add(Calendar.DAY_OF_MONTH, 1);
        cal.add(Calendar.MILLISECOND, -1);

        return cal.getTime();
    }

    /**
     * Clears the time component on a Calendar object. The
     * passed in Calendar object is updated.
     * @param cal The calendar object to clear.
     */
    public static void clearTime(Calendar cal) {
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.clear(Calendar.MINUTE);
        cal.clear(Calendar.SECOND);
        cal.clear(Calendar.MILLISECOND);
    }

    /**
     * Clears the time on a Date object. 
     * @param dt The input date.
     * @return A new date with the same date, but with the time cleared.
     */
    public static Date clearTime(Date dt) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        clearTime(cal);
        return cal.getTime();
    }
}

Related

  1. endOfDay(Date date)
  2. endOfDay(Date date)
  3. endOfDay(Date date)
  4. endOfDay(Date date)
  5. endOfDay(Date dateInst)
  6. endOfDay(Date inDate, TimeZone timeZone)
  7. endOfDay(Date value)
  8. endOfDay(final Date date)
  9. endOfDay(final Date date)