您当前的位置: 首页 >  Java

小志的博客

暂无认证

  • 3浏览

    0关注

    1217博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Java计算年月日时分秒时间差(两个时间相减)

小志的博客 发布时间:2018-03-29 13:49:12 ,浏览量:3

  1.   //测试主方法
  2.  public static void main(String[] args) {
  3.          Date currentTime = df.parse("2004-03-26 13:31:40");   //当前系统时间   
  4.          Date firstTime = df.parse("2004-01-02 11:30:24");     //查询的数据时间
  5.          String str=getTime(currentTime ,firstTime );
  6.          System.out.println("获取的年月日时分秒时间差为:"+str);
  7.   }
  8.   //获取时间差方法    
  9.   public static String getTime(Date currentTime,Date firstTime){
  10.           long diff = currentTime.getTime() - firstTime.getTime();//这样得到的差值是微秒级别
  11.           Calendar  currentTimes =dataToCalendar(currentTime);//当前系统时间转Calendar类型
  12.           Calendar  firstTimes =dataToCalendar(firstTime);//查询的数据时间转Calendar类型
  13.           int year = currentTimes.get(Calendar.YEAR) - firstTimes.get(Calendar.YEAR);//获取年
  14.           int month = currentTimes.get(Calendar.MONTH) - firstTimes.get(Calendar.MONTH);
  15.           int day = currentTimes.get(Calendar.DAY_OF_MONTH) - firstTimes.get(Calendar.DAY_OF_MONTH); 
  16.           if (day < 0) {
  17.              month -= 1;
  18.              currentTimes.add(Calendar.MONTH, -1);
  19.              day = day + currentTimes.getActualMaximum(Calendar.DAY_OF_MONTH);//获取日
  20.           }
  21.           if (month < 0) {
  22.              month = (month + 12) % 12;//获取月
  23.              year--;
  24.           }      
  25.           long days = diff / (1000 * 60 * 60 * 24);           
  26.           long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60); //获取时 
  27.           long minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);  //获取分钟
  28.           long s=(diff/1000-days*24*60*60-hours*60*60-minutes*60);//获取秒
  29.           String CountTime=""+"year"+"年"+month+"月"+day+"天"+hours+"小时"+minutes+"分"+s+"秒";
  30.           return CountTime;
  31.     }  
  32.     //Date类型转Calendar类型
  33.     public static Calendar dataToCalendar(Date date) {
  34.           Calendar calendar = Calendar.getInstance();
  35.           calendar.setTime(date);
  36.           return calendar;
  37.     }

关注
打赏
1661269038
查看更多评论
立即登录/注册

微信扫码登录

0.2084s