Set time to 00:00:00

前端 未结 12 2167
时光说笑
时光说笑 2020-11-29 20:04

I have a problem resetting hours in Java. For a given date I want to set the hours to 00:00:00.

This is my code :

/**
     * Resets milliseconds, se         


        
12条回答
  •  日久生厌
    2020-11-29 20:26

    Here are couple of utility functions I use to do just this.

    /**
     * sets all the time related fields to ZERO!
     *
     * @param date
     *
     * @return Date with hours, minutes, seconds and ms set to ZERO!
     */
    public static Date zeroTime( final Date date )
    {
        return DateTimeUtil.setTime( date, 0, 0, 0, 0 );
    }
    
    /**
     * Set the time of the given Date
     *
     * @param date
     * @param hourOfDay
     * @param minute
     * @param second
     * @param ms
     *
     * @return new instance of java.util.Date with the time set
     */
    public static Date setTime( final Date date, final int hourOfDay, final int minute, final int second, final int ms )
    {
        final GregorianCalendar gc = new GregorianCalendar();
        gc.setTime( date );
        gc.set( Calendar.HOUR_OF_DAY, hourOfDay );
        gc.set( Calendar.MINUTE, minute );
        gc.set( Calendar.SECOND, second );
        gc.set( Calendar.MILLISECOND, ms );
        return gc.getTime();
    }
    

提交回复
热议问题