Difference of two Joda LocalDateTimes

前端 未结 4 625
伪装坚强ぢ
伪装坚强ぢ 2020-12-19 01:28

I\'ve got 2 Joda LocalDateTime objects and need to produce a 3rd that represents the difference between them:

LocalDateTime start = getStartLoca         


        
4条回答
  •  醉梦人生
    2020-12-19 02:13

    I found a workaround by using following steps:

    1. Take two LocalDateTime objects as Start and End
    2. Convert both of them to Instant object such as start.toInstant(ZoneOffset.UTC);
    3. Calculate the Duration using Duration.between(instant t1, instant t2)
    4. Convert it into nanoseconds or milliseconds or seconds using various conversion methods. Nanoseconds can be calculated as Duration.toNanos()

    I have provided a full example below.

    public long getDuration(LocalDateTime start, LocalDateTime end) {
    
        //convert the LocalDateTime Object to an Instant 
        Instant startInstant = start.toInstant(ZoneOffset.UTC);         
        Instant endInstant   =   end.toInstant(ZoneOffset.UTC);
    
        //difference between two Instants is calculated
        //convert to nano seconds or milliseconds 
        long duration=Duration.between(startInstant, endInstant).toNanos();
    
        return duration;
    }
    

提交回复
热议问题