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

前端 未结 14 920
心在旅途
心在旅途 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:35

    private Date getStartOfDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DATE);
        calendar.setTimeInMillis(0);
        calendar.set(year, month, day, 0, 0, 0);
        return calendar.getTime();
        }
    
    private Date getEndOfDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DATE);
        calendar.setTimeInMillis(0);
        calendar.set(year, month, day, 23, 59, 59);
        return calendar.getTime();
        }
    

    calendar.setTimeInMillis(0); gives you accuracy upto milliseconds

提交回复
热议问题