最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

date - Convert Milliseconds to Timestamp "Time Ago" (59m, 5d, 3m, etc) in Javascript - Stack Overflow

programmeradmin1浏览0评论

I've seen a few examples using PHP but I am having some issues since I'm not too familiar with PHP and am on a time constraint.

I want to create a timestamp in which depending how long ago a post was created, it would display a different timestamp.

This is what I want:

  • If post was created less than a second ago, display: <1m;

  • If post was created between 1-59min ago, display : //# of minutes// + "m";

  • If post was created less than 1-24hrs ago, display: //# of hours// + "h";

  • If post was created 1-6 days ago, display: //# of days// + "d";

  • If post was created 1-3 weeks ago, display: //# of weeks// + "w";

  • If post was created 1-12 months ago, display: //# of months// + "m";

Here's the code I tried using:

function formatTime(timeCreated){


  var periods = ["second", "minute", "hour", "day", "week", "month", "year", "decade"];
  // var actualPeriods = ["m", "h", "d", "w", "m", "y"]
  var lengths = ["60","60","24","7","4.35","12","10"]
  var currentTime = Date.now()
  var difference = currentTime - timeCreated;

  for (var i = 0; difference >= lengths[i] && i < (lengths.length)-1; i++) {
    difference = difference /lengths[i];
  }


  difference = Math.round(difference)

  return difference + periods[i]
}

but formatTime(1508189037313) is returning 74year.

(1508189037313 is Mon 16 Oct 2017 16:23:57)

I saw an example that uses this in PHP

function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

but wasn't sure how to convert -> and => over to javascript.

Any help would be appreciated. Thank you!

I've seen a few examples using PHP but I am having some issues since I'm not too familiar with PHP and am on a time constraint.

I want to create a timestamp in which depending how long ago a post was created, it would display a different timestamp.

This is what I want:

  • If post was created less than a second ago, display: <1m;

  • If post was created between 1-59min ago, display : //# of minutes// + "m";

  • If post was created less than 1-24hrs ago, display: //# of hours// + "h";

  • If post was created 1-6 days ago, display: //# of days// + "d";

  • If post was created 1-3 weeks ago, display: //# of weeks// + "w";

  • If post was created 1-12 months ago, display: //# of months// + "m";

Here's the code I tried using:

function formatTime(timeCreated){


  var periods = ["second", "minute", "hour", "day", "week", "month", "year", "decade"];
  // var actualPeriods = ["m", "h", "d", "w", "m", "y"]
  var lengths = ["60","60","24","7","4.35","12","10"]
  var currentTime = Date.now()
  var difference = currentTime - timeCreated;

  for (var i = 0; difference >= lengths[i] && i < (lengths.length)-1; i++) {
    difference = difference /lengths[i];
  }


  difference = Math.round(difference)

  return difference + periods[i]
}

but formatTime(1508189037313) is returning 74year.

(1508189037313 is Mon 16 Oct 2017 16:23:57)

I saw an example that uses this in PHP

function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

but wasn't sure how to convert -> and => over to javascript.

Any help would be appreciated. Thank you!

Share Improve this question edited Nov 12, 2017 at 20:23 a--m 4,7821 gold badge41 silver badges60 bronze badges asked Nov 12, 2017 at 19:49 DresDres 1,5093 gold badges23 silver badges36 bronze badges 6
  • 1 You're not going to be able to directly transition that code to JavaScript - it relies on specific functionality of PHP's DateTime class. Consider something like Moment.js: momentjs./docs/#/displaying/fromnow – ceejayoz Commented Nov 12, 2017 at 19:52
  • equivalent to associative array is an object literal. {'y':'year',..., 's':'second'} – charlietfl Commented Nov 12, 2017 at 19:53
  • Note there are many many resources found in a web search for doing this. – charlietfl Commented Nov 12, 2017 at 19:54
  • i'd love to use moment.js but unfortunately we can't :( – Dres Commented Nov 12, 2017 at 19:54
  • 1 well you won't pull up php solutions if you use the word "javascript" in the search – charlietfl Commented Nov 12, 2017 at 20:09
 |  Show 1 more ment

2 Answers 2

Reset to default 6

Create some structure that stores the number of milliseconds for the various periods, subtract the date you're interested in from Date.now(), build an if structure checking to see if the difference is greater than the break point for the periods (from biggest to smallest) - then format some kind of output. If nothing matches you can return something indicating that it was more recent than one minute.

Note that the symbol you're using for minutes and months is the same.

var periods = {
  month: 30 * 24 * 60 * 60 * 1000,
  week: 7 * 24 * 60 * 60 * 1000,
  day: 24 * 60 * 60 * 1000,
  hour: 60 * 60 * 1000,
  minute: 60 * 1000
};

function formatTime(timeCreated) {
  var diff = Date.now() - timeCreated;

  if (diff > periods.month) {
    // it was at least a month ago
    return Math.floor(diff / periods.month) + "m";
  } else if (diff > periods.week) {
    return Math.floor(diff / periods.week) + "w";
  } else if (diff > periods.day) {
    return Math.floor(diff / periods.day) + "d";
  } else if (diff > periods.hour) {
    return Math.floor(diff / periods.hour) + "h";
  } else if (diff > periods.minute) {
    return Math.floor(diff / periods.minute) + "m";
  }
  return "Just now";
}
console.log(formatTime(Date.now()));
console.log(formatTime(1510507151026));
console.log(formatTime(1510517051026));
console.log(formatTime(1508189037313));

Did some more research, asked the right google questions, found This question also answered here and added some edits to fit my needs!

function formatTime(timeCreated) {

  var diff = Math.floor((Date.now() - timeCreated) / 1000);
  var interval = Math.floor(diff / 31536000);

  if (interval >= 1) {
    return interval + "y";
  }
  interval = Math.floor(diff / 2592000);
  if (interval >= 1) {
    return interval + "m";
  }
  interval = Math.floor(diff / 604800);
  if (interval >= 1) {
    return interval + "w";
  }
  interval = Math.floor(diff / 86400);
  if (interval >= 1) {
    return interval + "d";
  }
  interval = Math.floor(diff / 3600);
  if (interval >= 1) {
    return interval + "h";
  }
  interval = Math.floor(diff / 60);
  if (interval >= 1) {
    return interval + " m";
  }
  return "<1m";
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论