在JavaScript中显示2天之间的实时年,月,周和天 [英] Display real time years, months, weeks and days between 2 days in JavaScript

查看:56
本文介绍了在JavaScript中显示2天之间的实时年,月,周和天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我编写的代码,它似乎可以正常工作。

This is what I've coded it up, and it appears to work.

window.onload = function() {
   var currentSpan = document.getElementById('current');

   var minute = 60000,
       hour = minute * 60,
       day = hour * 24,
       week = day * 7,
       month = week * 4,
       year = day * 365;
       var start = new Date(2009, 6, 1);

   setInterval(function() {

       var now = new Date();



       var difference = now - start;


       var years = Math.floor(difference / year),
           months = Math.floor((difference - (years * year)) / month),
           weeks = Math.floor((difference - (months * month + years * year)) / week),
           days = Math.floor((difference - (weeks * week + months * month + years * year)) / day);



   currentSpan.innerHTML = 'Since has passed: ' + years + ' years, ' + months + ' months, ' + weeks + ' weeks and ' + days + ' days';

   }, 500);

};

这似乎可以更新我的跨度,并且所有数字 look 正确

This seems to update my span fine, and all the numbers look correct.

但是,代码看起来很难看。我真的需要像那样设置人造常量,然后进行所有数学运算来计算出我想要的吗?

However, the code looks quite ugly. Do I really need to set up faux constants like that, and then do all that math to calculate what I want?

Date 对象。

这是最好的方法吗?

推荐答案

您可以将这些常量放入数组中,然后对其进行迭代:

You could put those constants in an array and then just iterate through it:

function tdiff(utc) {
  var diff = new Date() - new Date(utc);
  var units = [
    1000 * 60 * 60 * 24 * 365,
    1000 * 60 * 60 * 24 * 28,
    1000 * 60 * 60 * 24 * 7,
    1000 * 60 * 60 * 24,
    1000 * 60 * 60,
    1000 * 60,
    1000
  ];

  var rv = [];
  for (var i = 0; i < units.length; ++i) {
    rv.push(Math.floor(diff / units[i]));
    diff = diff % units[i];
  }
  return rv;
}

当然,由于月份和年份的长度并不总是相同,因此确实不是那么准确,但我想您会意识到:-)

Of course since months and years aren't always the same length, this isn't really that accurate, but I figure you realize that :-)

也请参见: http://timeago.yarp.com/ 挺酷的

这篇关于在JavaScript中显示2天之间的实时年,月,周和天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆