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

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

    java.time

    Using java.time framework built into Java 8.

    import java.time.LocalTime;
    import java.time.LocalDateTime;
    
    LocalDateTime now = LocalDateTime.now(); // 2015-11-19T19:42:19.224
    // start of a day
    now.with(LocalTime.MIN); // 2015-11-19T00:00
    now.with(LocalTime.MIDNIGHT); // 2015-11-19T00:00
    // end of a day
    now.with(LocalTime.MAX); // 2015-11-19T23:59:59.999999999
    
    0 讨论(0)
  • 2020-11-27 10:49

    I think the easiest would be something like:

    // Joda Time
    
    DateTime dateTime=new DateTime(); 
    
    StartOfDayMillis = dateTime.withMillis(System.currentTimeMillis()).withTimeAtStartOfDay().getMillis();
    EndOfDayMillis = dateTime.withMillis(StartOfDayMillis).plusDays(1).minusSeconds(1).getMillis();
    

    These millis can be then converted into Calendar,Instant or LocalDate as per your requirement with Joda Time.

    0 讨论(0)
提交回复
热议问题