How to obtain the start time and end time of a day?

前端 未结 14 891
心在旅途
心在旅途 2020-11-27 10:23

How to obtain the start time and end time of a day?

code like this is not accurate:

 private Date getStartOfDay(Date date) {
    Calendar calendar =          


        
14条回答
  •  借酒劲吻你
    2020-11-27 10:30

    Another one solution which does not depend on any framework is:

    static public Date getStartOfADay(Date day) {
        final long oneDayInMillis = 24 * 60 * 60 * 1000;
        return new Date(day.getTime() / oneDayInMillis * oneDayInMillis);
    }
    
    static public Date getEndOfADay(Date day) {
        final long oneDayInMillis = 24 * 60 * 60 * 1000;
        return new Date((day.getTime() / oneDayInMillis + 1) * oneDayInMillis - 1);
    }
    

    Note that it returns UTC based time

提交回复
热议问题