【问题标题】:Convert yyyy-mm-dd hh:mm:ss format to time ago将 yyyy-mm-dd hh:mm:ss 格式转换为时间前
【发布时间】:2016-12-02 06:38:05
【问题描述】:

我有这个日期和时间格式2016-03-07 15:13:49。我想显示它就像 1 分钟前、1 小时前或 1 年前,具体取决于从现在开始的日期有多长。

【问题讨论】:

  • @RamanSahasi 重复问题的答案,是否适用于我的日期格式?
  • 你只需要转换你的时间格式。查看我的答案并运行代码 sn-p。

标签: javascript jquery


【解决方案1】:

您需要将日期格式转换为js date 对象,然后您可以使用this 答案中的timeSince 函数

var date = new Date('2016-03-07T15:13:49')

document.write("js date: " + date + "<br><br>");
document.write("timesince: ");

document.write(timeSince(date));

function timeSince(date) {

    var seconds = Math.floor((new Date() - date) / 1000);

    var interval = Math.floor(seconds / 31536000);

    if (interval > 1) {
        return interval + " years";
    }
    interval = Math.floor(seconds / 2592000);
    if (interval > 1) {
        return interval + " months";
    }
    interval = Math.floor(seconds / 86400);
    if (interval > 1) {
        return interval + " days";
    }
    interval = Math.floor(seconds / 3600);
    if (interval > 1) {
        return interval + " hours";
    }
    interval = Math.floor(seconds / 60);
    if (interval > 1) {
        return interval + " minutes";
    }
    return Math.floor(seconds) + " seconds";
}

【讨论】:

  • 谢谢,这就是解决方案。
  • 请注意,如果值介于 1 和 2 之间,则此函数将不会产生预期的输出,从而导致诸如“75 分钟”之类的结果。一个解决方法是使用 >= 如果比较
【解决方案2】:
var past_date = new Date('2016-07-28T05:13:49');    // the date will come here 
var time_diff = new Date()- past_date;     // getting the difference between the past date and the current date
var min = Math.floor(time_diff/60000); // Converting time in to minutes
var seconds = 59,
    minutes = Math.floor(min%60),
    hours = Math.floor(min/60);

if(hours > 24){ // Checking if the hours ids more than 24 to display as a day
   var days = hours/24;   
   days = days.toFixed(0);
   document.write("last updated:" + days + " days ago");
}else if(hours > 1){ // if time is less than the 24 hours it will display in hours
    document.write("last updated:" + hours + " hours ago");
}else{
    document.write("last updated:" + minutes + " minutes ago");
}

【讨论】:

    【解决方案3】:

    如果您不关心准确性,我认为moment 是更好的方法。

    例如:

    var m = require('moment');
    m("2016-03-07 15:13:49","YYYY-MM-DD HH:mm:ss").fromNow();  // 5 months ago
    m("2016-07-28 12:13:49","YYYY-MM-DD HH:mm:ss").fromNow();  // 2 hours ago
    m("2016-07-28 13:13:49","YYYY-MM-DD HH:mm:ss").fromNow();  // 36 minutes ago
    m("2016-07-28 13:49:00","YYYY-MM-DD HH:mm:ss").fromNow();  // a minute ago
    m("2016-07-28 13:50:00","YYYY-MM-DD HH:mm:ss").fromNow();  // a few seconds ago
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 2017-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多