栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

js计算两个日期间的天数月的实例代码

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

js计算两个日期间的天数月的实例代码

计算结果为几个月零几天


 
  计算天数月
  
 
 
 
   
开始日期:
结束日期:

Copyright (c) 2018 fhy
All Rights Reserved.

下面在通过一段代码看下js计算两个日期差

function timeDifc(start,end){
  let starts = new Date(start),ends = new Date(end),message = '';
  if (starts.getTime() > ends.getTime())
    return message = "现在的时间小于以前的时间!";
  if ((ends.getTime() - starts.getTime())/(1000*60) < 1)
    return message = "刚刚";
  if (ends.getFullYear() > starts.getFullYear() && ends.getMonth() >= starts.getMonth())
    message += ends.getFullYear() - starts.getFullYear() + "年";
  if (ends.getMonth() > starts.getMonth() && ends.getDate() >= starts.getDate())
    message += ends.getMonth() - starts.getMonth() + "个月";
  if (ends.getDate() > starts.getDate() && ends.getHours() >= starts.getHours())
    message += ends.getDate() - starts.getDate() + "天";
  if (ends.getHours() > starts.getHours() && ends.getMinutes() >= starts.getMinutes())
    message += ends.getHours() - starts.getHours() + "小时";
  if (ends.getMinutes() > starts.getMinutes())
    message += ends.getMinutes() - starts.getMinutes() + "分钟";
  return message;
};
// 注:上边的变量是用let声明的(es6语法),下边是用babel编译后的
function timeDifc(start, end) {
  var starts = new Date(start),
    ends = new Date(end),
    message = '';
  if (starts.getTime() > ends.getTime()) return message = "现在的时间小于以前的时间!";
  if ((ends.getTime() - starts.getTime()) / (1000 * 60) < 1) return message = "刚刚";
  if (ends.getFullYear() > starts.getFullYear() && ends.getMonth() >= starts.getMonth()) message += ends.getFullYear() - starts.getFullYear() + "年";
  if (ends.getMonth() > starts.getMonth() && ends.getDate() >= starts.getDate()) message += ends.getMonth() - starts.getMonth() + "个月";
  if (ends.getDate() > starts.getDate() && ends.getHours() >= starts.getHours()) message += ends.getDate() - starts.getDate() + "天";
  if (ends.getHours() > starts.getHours() && ends.getMinutes() >= starts.getMinutes()) message += ends.getHours() - starts.getHours() + "小时";
  if (ends.getMinutes() > starts.getMinutes()) message += ends.getMinutes() - starts.getMinutes() + "分钟";
  return message;
};

在浏览器的console中测试结果如下:

总结

以上所述是小编给大家介绍的js计算两个日期间的天数月的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/78966.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号