Java获取当天最小(00:00:00)最大(23:59:59)时间

Date

Calendar start = Calendar.getInstance();
start.set( Calendar.HOUR_OF_DAY,00);
start.set( Calendar.MINUTE, 0);
start.set( Calendar.SECOND,0);

Calendar end = Calendar.getInstance();
end.set(Calendar.HOUR_OF_DAY,23);
end.set( Calendar.MINUTE,59);
end.set(Calendar.SECOND,59);

SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("start:" + sm.format(start.getTime()));
System.out.println("end:" + sm.format(end.getTime()));

LocalDateTime

public static void main(String[] args) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("当前时间:" + sdf.format(date));
        System.out.println("==============================");
        System.out.println("今天开始时间:" + sdf.format(getStartOfDay(date)));
        System.out.println("今天结束时间:" + sdf.format(getEndOfDay(date)));
    }

    /**
     * 
     * @description: 获得当天最小时间
     * @author: Jeff
     * @date: 2019年12月21日
     * @param date
     * @return
     */
    public static Date getStartOfDay(Date date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()),
                ZoneId.systemDefault());
        LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);
        return Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 
     * @description: 获得当天最大时间
     * @author: Jeff
     * @date: 2019年12月21日
     * @param date
     * @return
     */
    public static Date getEndOfDay(Date date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()),
                ZoneId.systemDefault());
        LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
        return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
    }

来源

LocalDateTime
Date

你可能感兴趣的