java计算时间差及比较时间

java计算时间差及比较时间

编程入门hacker2018-05-24 8:31:058671A+A-

例如:如今是2004-03-26 13:31:40

       以往是:2004-01-02 11:30:24

如果你要得到2个时间差,差的方式为:XX天XX钟头XX分XX秒

方式一:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

try

{

    Date d1 = df.parse("2004-03-26 13:31:40");

    Date d2 = df.parse("2004-01-02 11:30:24");

    long diff = d1.getTime() - d2.getTime();

    long days = diff / (1000 * 60 * 60 * 24);

}

catch (Exception e)

{

}

方式二:

   SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

   java.util.Date now = df.parse("2004-03-26 13:31:40");

   java.util.Date date=df.parse("2004-01-02 11:30:24");

   long l=now.getTime()-date.getTime();

   long day=l/(24*60*60*1000);

   long hour=(l/(60*60*1000)-day*24);

   long min=((l/(60*1000))-day*24*60-hour*60);

   long s=(l/1000-day*24*60*60-hour*60*60-min*60);

   System.out.println(""+day+"天"+hour+"钟头"+min+"分"+s+"秒");

方式三:

   SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

   java.util.Date begin=dfs.parse("2004-01-02 11:30:24");

   java.util.Date end = dfs.parse("2004-03-26 13:31:40");

   long between=(end.getTime()-begin.getTime())/1000;//除于1000是以便转化成秒

   long day1=between/(24*3600);

   long hour1=between%(24*3600)/3600;

   long minute1=between%3600/60;

   long second1=between%60/60;

   System.out.println(""+day1+"天"+hour1+"钟头"+minute1+"分"+second1+"秒");

====================================================

java 较为時间尺寸

String s1="2008-01-25 09:12:09";

String s2="2008-01-29 09:12:11";

java.text.DateFormat df=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

java.util.Calendar c1=java.util.Calendar.getInstance();

java.util.Calendar c2=java.util.Calendar.getInstance();

try

{

c1.setTime(df.parse(s1));

c2.setTime(df.parse(s2));

}catch(java.text.ParseException e){

System.err.println("文件格式有误");

}

int result=c1.compareTo(c2);

if(result==0)

System.out.println("c1相同c2");

else if(result<0)

System.out.println("c1低于c2");


点击这里复制本文地址 以上内容由黑资讯整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
  • 1条评论
  • 鸽吻清妩2022-05-28 06:30:19
  • at dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   java.util.Date

支持Ctrl+Enter提交

黑资讯 © All Rights Reserved.  
Copyright Copyright 2015-2020 黑资讯
滇ICP备19002590号-1
Powered by 黑客资讯 Themes by 如有不合适之处联系我们
网站地图| 发展历程| 留言建议| 网站管理