本文主要是介绍两个日期相差多少时间, 精确到秒,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用joda-time 来查询两个日期相差多少时间, 精确到秒
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;
import org.joda.time.Interval;
import org.joda.time.Minutes;
import org.joda.time.Period;
import org.joda.time.Seconds;/*** Created by csucoderlee on 2017 10 16 10:39.*/
public class Test2 {public static void test1(Date d1, Date d2) {// 毫秒mslong diff = d2.getTime() - d1.getTime();long diffSeconds = diff / 1000 % 60;long diffMinutes = diff / (60 * 1000) % 60;long diffHours = diff / (60 * 60 * 1000) % 24;long diffDays = diff / (24 * 60 * 60 * 1000);System.out.print("时间相差:");System.out.print(diffDays + " 天 ");System.out.print(diffHours + " 小时 ");System.out.print(diffMinutes + " 分钟 ");System.out.print(diffSeconds + " 秒.");System.out.println();}public static void test2(Date d1, Date d2) throws ParseException {DateTime dt1 = new DateTime(d1);DateTime dt2 = new DateTime(d2);System.out.print("时间相差:");System.out.print(Days.daysBetween(dt1, dt2).getDays() + " 天 ");System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " 小时 ");System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " 分钟 ");System.out.print(Seconds.secondsBetween(dt1, dt2).getSeconds() % 60 + " 秒.");System.out.println();}public static void test3(Date d1, Date d2) {Interval interval = new Interval(d1.getTime(), d2.getTime());Period p = interval.toPeriod();System.out.println("时间相差:" + p.getDays() + " 天 " + p.getHours() + " 小时 " + p.getMinutes() + " 分钟" + p.getSeconds() + " 秒");}/*** @param args* @throws ParseException*/public static void main(String[] args) throws ParseException {String dateStart = "2013-08-13 16:29:58";String dateStop = "2013-08-13 16:31:48";SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date d1 = format.parse(dateStart);Date d2 = format.parse(dateStop);test1(d1, d2);test2(d1, d2);test3(d1, d2);}
}
原文,链接
http://1985wanggang.blog.163.com/blog/static/7763833201371341545546/
这篇关于两个日期相差多少时间, 精确到秒的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!