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

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

    For java 8 the following single line statements are working. In this example I use UTC timezone. Please consider to change TimeZone that you currently used.

    System.out.println(new Date());
    
    final LocalDateTime endOfDay       = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
    final Date          endOfDayAsDate = Date.from(endOfDay.toInstant(ZoneOffset.UTC));
    
    System.out.println(endOfDayAsDate);
    
    final LocalDateTime startOfDay       = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
    final Date          startOfDayAsDate = Date.from(startOfDay.toInstant(ZoneOffset.UTC));
    
    System.out.println(startOfDayAsDate);
    

    If no time difference with output. Try: ZoneOffset.ofHours(0)

提交回复
热议问题