JS转换时间字符串为人性化时间格式 – Falost的小窝
  • 欢迎关注我的微信公众号“ frontEnd_Developer ” 右边扫描关注 --->>

JS转换时间字符串为人性化时间格式

JavaScript 神棍 341℃

作为一个前端,对于date的数据处理是经常难免的,后台传回了一个类似于 Fri Jan 13 2017 18:36:34 GMT+0800 (中国标准时间)  或 2017/1/13 这种时间格式让前台处理成人性化的时间,比如:

几天前,几个月前,刚刚,几小时前,几年前,等等,这种格式的
就需要敲一坨代码出来,无非就是对数据进行时间格式化(1484303794000),然后在做判断处理下就可以达到了。具体看代码:

var date = new Date();
    console.log(date);
    console.log(moment(date))
    function moment(context){
      //console.log(context)
      var minute = 1000 * 60;
      var hour = minute * 60;
      var day = hour * 24;
      var month = day * 30;
      var now = new Date().getTime();
      function getDateDiff(dateTimeStamp) {
        console.log(dateTimeStamp);
        var diffValue = now - dateTimeStamp;
        console.log(new Date(dateTimeStamp).toLocaleDateString())
        console.log(diffValue)
        if (diffValue < 0) {
          result = new Date(dateTimeStamp).toLocaleDateString();
        }
        var yearComment = diffValue /(month * 12)
        var monthComment = diffValue / month;
        var weekComment = diffValue / (7 * day);
        var dayComment = diffValue / day;
        var hourComment = diffValue / hour;
        var minComment = diffValue / minute;
        //console.log(yearComment);
        if(yearComment >= 1){
          result = parseInt(yearComment) + "年前";
        } else if (monthComment < 4 && monthComment >= 1) {
          result = parseInt(monthComment) + "个月前";
        } else if (weekComment >= 1) {
          result = parseInt(weekComment) + "周前";
        } else if (dayComment >= 1) {
          result = parseInt(dayComment) + "天前";
        } else if (hourComment >= 1) {
          result = parseInt(hourComment) + "小时前";
        } else if (minComment >= 1) {
          result = parseInt(minComment) + "分钟前";
        } else if(minComment < 0){
            result = "还未发生"
        } else
          result = "刚刚";
        return result;
      }
      return getDateDiff(Date.parse(context))
    }

最后给大家推荐一款JavaScript 日期处理类(内)库 (Moment.js)

官方地址:http://momentjs.cn/

具体使用方法情况官方文档:http://momentjs.cn/

转载请注明:Falost的小窝 » JS转换时间字符串为人性化时间格式

如果你觉得这篇文章不错或者对你有帮助,想请我喝一杯咖啡,可以打赏
喜欢 (1)