简体   繁体   中英

Convert exact date to time ago using jquery - What format for the date?

I have a static page which will specify a hardcoded exact date. If the use has javascript, I want to then convert this hardcoded exact date into a "time ago".

For example:

3 hours ago

My question is, in what format of date will javascript be able to most efficiently convert to the time ago?

  • 10/10/13
  • 10.10.13
  • 10th October 2013
  • 101013

I would look at this post: https://stackoverflow.com/a/3177838/2895307

In it he just uses a javascript Date() as the parameter to the "timeSince()" function. To create a javascript Date from your hardcoded string you can use this format:

var d1 = new Date("October 13, 1975 11:13:00")

definitely unix timestamp is the best format for all date and time calculations, you can convert the results to a more readable format later.

the calculation is simple, you start with the timestamp of an event in the past, for example:

var anHourAgo = Date.now() - 3600000;

then you substract that from the current timestamp and get the number of milliseconds that have passed since that event

Date.now() - anHourAgo

then you can pass that to any function that will convert those milliseconds to hours, minutes and seconds, here's an example that takes seconds and returns an array with that info, and another function that pads those numbers with zeros

var zeroPad = function(n){
    return n.toString().replace(/^(\d)$/,'0$1');
};

var formatSecs = function(s){
    var r = [
        Math.floor(s / 3600),
        Math.floor(s%3600 / 60),
        Math.floor((s%3600)%60)
    ];
    r.push(zeroPad(r[0])+':'+zeroPad(r[1])+':'+zeroPad(r[2]));
    return r;
};

the formatSecs function expects seconds instead of millseconds, you should divide by 1000 and round that number, then pass that number to the function

Math.round(Date.now() - anHourAgo) / 1000

Finally here's a working example of all that code in action:

http://codepen.io/DavidVValdez/pen/axHGj

i hope this helps, cheers!

The easiest thing to do would be to use Date.getTime() .

This will give you the number of milliseconds since the Unix epoch and will make the math very simple.

Date.getTime

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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