简体   繁体   English

使用javascript计算经过的时间

[英]Calculate time elapsed using javascript

I want to calculate time elapsed since my birthday in the form of (years, months, days, hours, minutes, seconds) using JavaScript.我想使用 JavaScript 以(年、月、日、小时、分钟、秒)的形式计算自我生日以来经过的时间。

For example, my birth date is 15-Oct-1989, 00 hrs 00 mins 00 secs.例如,我的出生日期是 15-Oct-1989,00 小时 00 分 00 秒。 Hence, time elapsed since my birth date is,因此,从我的出生日期起经过的时间是,

22 years 5 months 10 days 19 hours 25 minutes 25 seconds 

I want to achieve the same output using JavaScript code.我想使用 JavaScript 代码实现相同的输出。 Any link or so will certainly help in this case.在这种情况下,任何链接都肯定会有所帮助。

Try something like this:尝试这样的事情:

var now = new Date();
var bDay = new Date(1989, 10, 15);
var elapsedT = now - bDay; // in ms

Read MDN for further info.阅读MDN以获取更多信息。 That'll give you some idea how to format the result.这会给你一些想法如何格式化结果。

Since my previous answer has people missing the point entirely, here's a port of PHP code I have to do the same thing:由于我之前的回答让人们完全忽略了这一点,这里有一个 PHP 代码端口,我必须做同样的事情:

function getDaysInMonth(month,year) {     
    if( typeof year == "undefined") year = 1999; // any non-leap-year works as default     
    var currmon = new Date(year,month),     
        nextmon = new Date(year,month+1);
    return Math.floor((nextmon.getTime()-currmon.getTime())/(24*3600*1000));
} 
function getDateTimeSince(target) { // target should be a Date object
    var now = new Date(), diff, yd, md, dd, hd, nd, sd, out = [];
    diff = Math.floor(now.getTime()-target.getTime()/1000);
    yd = target.getFullYear()-now.getFullYear();
    md = target.getMonth()-now.getMonth();
    dd = target.getDate()-now.getDate();
    hd = target.getHours()-now.getHours();
    nd = target.getMinutes()-now.getMinutes();
    sd = target.getSeconds()-now.getSeconds();
    if( md < 0) {yd--; md += 12;}
    if( dd < 0) {
        md--;
        dd += getDaysInMonth(now.getMonth()-1,now.getFullYear());
    }
    if( hd < 0) {dd--; hd += 24;}
    if( md < 0) {hd--; md += 60;}
    if( sd < 0) {md--; sd += 60;}

    if( yd > 0) out.push( yd+" year"+(yd == 1 ? "" : "s"));
    if( md > 0) out.push( md+" month"+(md == 1 ? "" : "s"));
    if( dd > 0) out.push( dd+" day"+(dd == 1 ? "" : "s"));
    if( hd > 0) out.push( hd+" hour"+(hd == 1 ? "" : "s"));
    if( nd > 0) out.push( nd+" minute"+(nd == 1 ? "" : "s"));
    if( sd > 0) out.push( sd+" second"+(sd == 1 ? "" : "s"));
    return out.join(" ");
}

Example:例子:

getDateTimeSince(new Date(1992,1,6,22,30,00)); 
// my date of birth - near enough half past ten in the evening on Feb 6th 1992
> 20 years 1 month 18 days 17 hours 23 minutes 7 seconds

I believe this is exactly what the OP was asking for.我相信这正是OP 所要求的。

First of all, what you demand is a bit imprecise.首先,你的要求有点不精确。 We know that a minute = 60 seconds, a hour = 60 minutes... And it stops here.我们知道一分钟 = 60 秒,一小时 = 60 分钟......它停在这里。 A day can be either 24 or just a little more than 24 hours, depending how you treat leap years, and "one month" doesn't even try to represent a time span precisely.一天可以是 24 小时,也可以是 24 小时多一点,这取决于您如何对待闰年,而“一个月”甚至没有尝试精确表示时间跨度。

Hence: Either keep your timespans as hours, or establish an approximation to deal with leap years etc. Dates and date differences (timespans) are different concepts and need to always be treated differently.因此:要么保持时间跨度为小时,要么建立一个近似值来处理闰年等。日期和日期差异(时间跨度)是不同的概念,需要始终区别对待。

Anyway, as for the code, I'd simply go for :无论如何,至于代码,我只是去:

var ms = new Date() - yourBirthDate;
var secs = ms/1000;

var minutes = secs    / 60 ;  secs    = secs    % 60;
var hours   = minutes / 60 ;  minutes = minutes % 60;
// and so on if you want

Use Moment.js for parsing, validating, manipulating, and formatting dates in Javascript.使用 Moment.js 在 Javascript 中解析、验证、操作和格式化日期。 Only 5.5k so not much of a good reason to do this kind of low-level code yourself these days.现在只有 5.5k,所以不是自己编写这种低级代码的充分理由。

http://momentjs.com/ http://momentjs.com/

function getDaysInMonth(month,year) {     
    if( typeof year == "undefined") year = 1999; // any non-leap-year works as default     
    var currmon = new Date(year,month),     
        nextmon = new Date(year,month+1);
    return Math.floor((nextmon.getTime()-currmon.getTime())/(24*3600*1000));
} 
function getDateTimeSince(target) { // target should be a Date object
    var now = new Date(), yd, md, dd, hd, nd, sd, out = []; 

    yd = now.getFullYear()-target.getFullYear();
    md = now.getMonth()-target.getMonth();
    dd = now.getDate()-target.getDate();
    hd = now.getHours()-target.getHours();
    nd = now.getMinutes()-target.getMinutes();
    sd = now.getSeconds()-target.getSeconds(); 

    if( md < 0) {yd--; md += 12;}
    if( dd < 0) {
        md--;
        dd += getDaysInMonth(now.getMonth()-1,now.getFullYear());
    }
    if( hd < 0) {dd--; hd += 24;}
    if( nd < 0) {hd--; nd += 60;}
    if( sd < 0) {nd--; sd += 60;}

    if( yd > 0) out.push( yd+" year"+(yd == 1 ? "" : "s"));
    if( md > 0) out.push( md+" month"+(md == 1 ? "" : "s"));
    if( dd > 0) out.push( dd+" day"+(dd == 1 ? "" : "s"));
    if( hd > 0) out.push( hd+" hour"+(hd == 1 ? "" : "s"));
    if( nd > 0) out.push( nd+" minute"+(nd == 1 ? "" : "s"));
    if( sd > 0) out.push( sd+" second"+(sd == 1 ? "" : "s"));
    return out.join(" ");
}

This is a different version of Kolink's Code.这是 Kolink 代码的不同版本。 There were a number of errors in his that stopped this script from working correctly...他的许多错误阻止了这个脚本正常工作......

Take a look at the JavaScript Date object .查看JavaScript Date 对象 Specifically, on that page, look for the "Calculate Elapsed Time" section (near the bottom):具体来说,在该页面上,查找“计算经过时间”部分(靠近底部):

// using static methods
var start = Date.now();
// the event you'd like to time goes here:
doSomethingForALongTime();
var end = Date.now();
var elapsed = end - start; // time in milliseconds

In your case, the start would be a given date:在您的情况下, start将是给定的日期:

var start = new Date(1989,10,15);

If you want to calculate to the number of days, or even weeks, you can do this just by subtracting the current timestamp from your birthday's timestamp and divide the number into its component time units.如果您想计算天数,甚至是周数,您只需从生日的时间戳中减去当前的时间戳,然后将数字划分为其组成时间单位即可。

However if you want months and years, it's a bit more complicated due to the variable number of days in a month.但是,如果您想要数月和数年,由于一个月中的天数可变,这就有点复杂了。

Perhaps the easiest way to go about it is as follows:也许最简单的方法如下:

  1. Get the difference in years (currentYear - birthYear)获取年差(currentYear -birthYear)
  2. Get the difference in months (currentMonth - birthMonth)获取月差(currentMonth -birthMonth)
  3. Repeat for all units对所有单位重复
  4. If any unit is negative, subtract 1 from the unit above and add however many of the current unit make up the bigger unit.如果任何单位为负,则从上面的单位中减去 1,然后加上当前单位的许多组成更大的单位。

The complication arises when you want to find how many days are in a given month.当您想要查找给定月份中有多少天时,就会出现复杂情况。 This can help:这可以帮助:

function getDaysInMonth(month,year) {
    if( typeof year == "undefined") year = 1999; // any non-leap-year works as default
    var currmon = new Date(year,month),
        nextmon = new Date(year,month+1); // no need to check for December overflow - JS does this automatically
    return Math.floor((nextmon.getTime()-currmon.getTime())/24*3600);
}

This should be enough to get you on the right track.这应该足以让您走上正轨。 Let me know if you need any more help.如果您需要更多帮助,请告诉我。

Here is an easy way to calculate elapsed time.这是计算经过时间的简单方法。

  1. Calculate difference between origin date and today in milliseconds以毫秒为单位计算原始日期和今天之间的差异
  2. Pass this difference to a Date object called result将此差异传递给名为 result 的 Date 对象
  3. Remember from Date Object definition that that result object is milliseconds from 01/01/1970 00:00:00.从日期对象定义中记住,结果对象是从 01/01/1970 00:00:00 开始的毫秒数。
  4. Inspect this result object to get Years, Months, and so on.检查此结果对象以获取 Years、Months 等。

Here is the code to do so.这是执行此操作的代码。

Date.prototype.getElapsedTime = function() {
  var diffDate = new Date(Date.now() - this);
  return "Elapsed Time: Years: " + (diffDate.getFullYear() - 1970) + ", Months: " + diffDate.getMonth() + ", Days: " + (diffDate.getDate() - 1) + ", Hours: " + diffDate.getHours() + ", Minutes: " + diffDate.getMinutes() + ", Seconds: " + diffDate.getSeconds();
};

var from = new Date("01/08/1986 04:07:00");
document.getElementById("result").innerHTML = from.getElapsedTime();

Here is something you can play around with: https://jsfiddle.net/nishchal/u8gt2gwq/4/这里有一些你可以玩的东西: https : //jsfiddle.net/nishchal/u8gt2gwq/4/

I like this one:我喜欢这个:

function lifeSpan(t0) {var x=new Date()-t0, a=x, i=0,s=0,m=0,h=0,j=0;
  if(a>=1){i=a%1000;a=(a-i)/1000;
  if(a>=1){s=a%60;a=(a-s)/60;
  if(a>=1){m=a%60;a=(a-m)/60;
  if(a>=1){h=a%24;a=(a-h)/24;
  if(a>=1){j=a;//...
  }}}}}
  return 'Elapsed: '+i+'ms '+s+'s '+m+'mn '+h+'h '+j+'j (or '+x+'ms).';}

Here is a quick algorithm for displaying time elapsed since a unix/epoch timestamp:这是显示自 unix/epoch 时间戳以来经过的时间的快速算法:

 const showElapsedTime = (timestamp) => { if (typeof timestamp !== 'number') return 'NaN' const SECOND = 1000 const MINUTE = 1000 * 60 const HOUR = 1000 * 60 * 60 const DAY = 1000 * 60 * 60 * 24 const MONTH = 1000 * 60 * 60 * 24 * 30 const YEAR = 1000 * 60 * 60 * 24 * 30 * 12 const elapsed = ((new Date()).valueOf() - timestamp) if (elapsed <= MINUTE) return `${Math.round(elapsed / SECOND)}s` if (elapsed <= HOUR) return `${Math.round(elapsed / MINUTE)}m` if (elapsed <= DAY) return `${Math.round(elapsed / HOUR)}h` if (elapsed <= MONTH) return `${Math.round(elapsed / DAY)}d` if (elapsed <= YEAR) return `${Math.round(elapsed / MONTH)}mo` return `${Math.round(elapsed / YEAR)}y` } const createdAt = 1541301301000 console.log(showElapsedTime(createdAt + 5000000)) console.log(showElapsedTime(createdAt)) console.log(showElapsedTime(createdAt - 500000000))

(new Date()).valueOf() returns the number of seconds elapsed since Jan 1, 1970. (new Date()).valueOf()返回自 1970 年 1 月 1 日以来经过的秒数。

After you get that, you just need the timestamp of your event, and you can subtract it from the current time.获得之后,您只需要事件的时间戳,您就可以从当前时间中减去它。 This leaves the number of seconds elapsed, which can be converted into a human readable format by dividing by the correct number of units.这留下了经过的秒数,可以通过除以正确的单位数将其转换为人类可读的格式。

For example, 3000 milliseconds is 300 seconds.例如,3000 毫秒就是 300 秒。 The algorithm I showed works with millisecond timestamps (divide everything by 1000 for seconds), so in the algorithm, 3000 would be be greater than MINUTE but less than HOUR , so it would return 3000 / MINUTE and return 3s .我展示的算法适用于毫秒时间戳(将所有内容除以 1000 秒),因此在算法中, 3000 将大于MINUTE但小于HOUR ,因此它将返回3000 / MINUTE并返回3s

This algorithm is useful if you are displaying a card, such as a job posting that was posted 2d ago .如果您要显示卡片,例如2d ago发布的职位发布,则此算法很有用。

I didn't like most of the other answers I found because they were not simple enough or readable enough.我不喜欢我找到的大多数其他答案,因为它们不够简单或可读性不够。 I hope my answer is quickly understandable.我希望我的回答很快就会被理解。

Here is simple algorithm for finding the elapse time:这是用于查找经过时间的简单算法:

 time_elapsed_string = function(ptime){ var etime = (Date.now() / 1000 | 0 ) - ptime; if (etime < 1) { return '0 seconds'; } var a = {'31536000' : 'year', '2592000' : 'month', '86400' : 'day', '3600' : 'hour', '60' : 'minute', '1' : 'second' }; var a_plural = { 'year' : 'years', 'month' : 'months', 'day' : 'days', 'hour' : 'hours', 'minute' : 'minutes', 'second' : 'seconds' }; var output = ''; $.each(a,function(secs,str){ var d = etime / secs; if (d >= 1){ var r = Math.round(d); output = r + ' ' + (r > 1 ? a_plural[str] : str) + ' ago'; return true; } }); return output; }

I came up with the following:我想出了以下内容:

let getTimeElpasedString = (datetime, depth=1 )=>{
    /*
        depth = 0 means start at milliseconds
        depth = 1 means start at seconds
        ...
    */
    datetime = Date.parse(datetime).getElapsed()
    console.log(datetime)
    let dividers = [1000, 60, 60, 24, 7]
    let str = ''
    let units = ["milliseconds", "seconds", "minutes", "hours", "days"]
    let reminders = []
    dividers.forEach(d=>{
        reminders.push(datetime % d)
        datetime = parseInt(datetime/d) 
    })
    reminders = reminders.slice(depth).reverse()
    units = units.slice(depth).reverse()
    for(let i=0; i<reminders.length; i++){
        // skip which is equal to zero
        if(reminders[i] != 0)
            str += `${reminders[i]} ${units[i]} `
    }
    return str + "ago"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM