如何获得以秒为单位的时差?
How to get the time difference in seconds?
我用过 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);
这显示了日期差异。但是如果我给同一个日期的不同时间进行比较,那就是returns0。
LocalDate
is just that, date only, no time information. Use 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
我用过 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);
这显示了日期差异。但是如果我给同一个日期的不同时间进行比较,那就是returns0。
LocalDate
is just that, date only, no time information. Use 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