如何在几秒钟内获得时差?

时间:2015-03-04 04:14:15

标签: java datetime jodatime

我使用过Jodha Library并尝试在几秒钟内获得两个日期之间的差异。但它只是准确到日期。不到秒。

 public static int getDateDifference(DateTime dateCreatedPa)
    {
        LocalDate dateCreated = new LocalDate (dateCreatedPa);
        LocalDate now = new LocalDate();

        Seconds secondsBetween = Seconds.secondsBetween(dateCreated, now);

        return secondsBetween.getSeconds();
    }
       ///code calling the above method

        DateTime dateCreated=new DateTime(drivingLicense.getDateCreated());
        int dateDiff=Common.getDateDifference(dateCreated);            
        request.setAttribute("dateDiff", dateDiff);

        System.out.println("Timestamp: "+dateDiff);

显示日期差异。但是如果我在同一天给出不同的时间进行比较,它会返回0.

1 个答案:

答案 0 :(得分:1)

LocalDate只是日期,没有时间信息。请改用LocalDateTime

import org.joda.time.DateTime;
import org.joda.time.LocalDateTime;
import org.joda.time.Seconds;

public class Test {

    public static void main(String[] args) {

        DateTime today = DateTime.now();
        today = today.minusDays(5);
        int dateDiff = getDateDifference(today);
        System.out.println("Timestamp: " + dateDiff);
    }

    public static int getDateDifference(DateTime dateCreatedPa) {
        LocalDateTime dateCreated = new LocalDateTime(dateCreatedPa);
        LocalDateTime now = new LocalDateTime();

        System.out.println(dateCreated);
        System.out.println(now);

        Seconds secondsBetween = Seconds.secondsBetween(dateCreated, now);

        return secondsBetween.getSeconds();
    }

}

...输出

2015-02-27T15:20:56.524
2015-03-04T15:20:56.628
Timestamp: 432000