给定一个特定的时间,我怎么能把它转换到前一段时间?

时间:2016-10-15 05:04:06

标签: javascript

考虑到这种类型的时间" 2015-02-01T08:45:23Z ",

如何在Javascript中将其转换为Time?

3 个答案:

答案 0 :(得分:2)

使用momentjs javascript插件。

moment("2015-02-01T08:45:23Z").startOf('day').fromNow();

答案 1 :(得分:0)

使用普通的javascript你可以尝试类似的东西:

function since(then) {
  var difference = new Date((new Date()) - then),
    values = [(difference.getYear() - (new Date(0)).getYear()), difference.getMonth(), difference.getDay(), difference.getHours(), difference.getMinutes(), difference.getSeconds(), difference.getMilliseconds()],
    labels = ["Years", "Months", "Days", "Hours", "Minutes", "Seconds", "MilliSeconds"]
  return labels.map(function(e, i) {
    return values[i] > 0 ? values[i] + " " + e + " " : "";
  }).join("");
}
console.log(since(new Date("2015-02-01T08:45:23Z")));

momentjs也是一个不错的选择,你可以参考另一个答案看看它是如何使用的

答案 2 :(得分:-1)

试试这个;)

您可以尝试livestamp插件,您需要jQuery(> = 1.7)和Moment.js(> = 1.7)。

// Livestamp.js / v1.1.2 / (c) 2012 Matt Bradley / MIT License
(function(d,g){var h=1E3,i=!1,e=d([]),j=function(b,a){var c=b.data("livestampdata");"number"==typeof a&&(a*=1E3);b.removeAttr("data-livestamp").removeData("livestamp");a=g(a);g.isMoment(a)&&!isNaN(+a)&&(c=d.extend({},{original:b.contents()},c),c.moment=g(a),b.data("livestampdata",c).empty(),e.push(b[0]))},k=function(){i||(f.update(),setTimeout(k,h))},f={update:function(){d("[data-livestamp]").each(function(){var a=d(this);j(a,a.data("livestamp"))});var b=[];e.each(function(){var a=d(this),c=a.data("livestampdata");
  if(void 0===c)b.push(this);else if(g.isMoment(c.moment)){var e=a.html(),c=c.moment.fromNow();if(e!=c){var f=d.Event("change.livestamp");a.trigger(f,[e,c]);f.isDefaultPrevented()||a.html(c)}}});e=e.not(b)},pause:function(){i=!0},resume:function(){i=!1;k()},interval:function(b){if(void 0===b)return h;h=b}},l={add:function(b,a){"number"==typeof a&&(a*=1E3);a=g(a);g.isMoment(a)&&!isNaN(+a)&&(b.each(function(){j(d(this),a)}),f.update());return b},destroy:function(b){e=e.not(b);b.each(function(){var a=
  d(this),c=a.data("livestampdata");if(void 0===c)return b;a.html(c.original?c.original:"").removeData("livestampdata")});return b},isLivestamp:function(b){return void 0!==b.data("livestampdata")}};d.livestamp=f;d(function(){f.resume()});d.fn.livestamp=function(b,a){l[b]||(a=b,b="add");return l[b](this,a)}})(jQuery,moment);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://momentjs.com/downloads/moment.js"></script>
<script src="https://raw.githubusercontent.com/mattbradley/livestampjs/1.1.2/livestamp.min.js"></script>

<span data-livestamp="2016-10-14T08:45:23Z"></span>