获取JavaScript

时间:2018-04-29 00:38:17

标签: javascript jquery

我想编写一个JavaScript函数,它将比较2个日期值(startdate& now)然后显示: -

  1. 剩下的几个月&周。

  2. 如果开始日期与当月相同,则显示剩余的周数和时间。天。

  3. 如果开始日期与当前周相同,则显示重命名日期。

  4. 现在我找到了这个脚本:

    var nurl = items[i].CounterStartDate.toString();
    var countDownDate = new Date(nurl).getTime();
    
    
    var now = new Date().getTime();
    
    // Find the distance between now an the count down date
    var distance = countDownDate - now;
    
    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    

    将显示剩余的天数,小时数,分钟数和秒数。但我不确定如何修改它以匹配我的上述3分?

    提示。我使用的日期值来自rest api,它将具有以下格式2019-05-24T23:00:00Z2018-06-20T23:00:00Z等。

1 个答案:

答案 0 :(得分:2)

我认为这个功能会做你想要的。

function datediff(date) {
   let d1 = date;
   let d2 = now = new Date();
   if (d2.getTime() < d1.getTime()) {
     d1 = now;
     d2 = date;
   }
   let yd = d1.getYear();
   let yn = d2.getYear();
   let years = yn - yd;
   let md = d1.getMonth();
   let mn = d2.getMonth();
   let months = mn - md;
   if (months < 0) {
     years--;
     months = 12 - md + mn;
   }
   let dd = d1.getDate();
   let dn = d2.getDate();
   let days = dn - dd;
   if (days < 0) {
     months--;
     // figure out how many days there are in the last month
     d2.setMonth(mn, 0);
     days = d2.getDate() - dd + dn;
   }
   let weeks = Math.floor(days / 7);
   days = days % 7;
   if (years > 0) return years + ' years' + (months > 0 ? ' and ' + months + ' months' : '');
   if (months > 0) return months + ' months' + (weeks > 0 ? ' and ' + weeks + ' weeks' : '');
   if (weeks > 0) return weeks + ' weeks' + (days > 0 ? ' and ' + days + ' days' : '');
   return days + ' days';
}

输出:

console.log(datediff(new Date('2018-04-24')))
5 days
console.log(datediff(new Date('2018-04-04')))
3 weeks and 4 days
console.log(datediff(new Date('2018-03-30')))
4 weeks and 2 days
console.log(datediff(new Date('2018-03-28')))
1 months
console.log(datediff(new Date('2018-03-20')))
1 months and 1 weeks
console.log(datediff(new Date('2017-12-03')))
4 months and 3 weeks
console.log(datediff(new Date('2017-02-03')))
1 years and 2 months
console.log(datediff(new Date('2018-05-12')))
1 weeks and 5 days