React实战之将数据库返回的时间转换为几分钟前、几小时前、几天前的形式。?

React实战之将数据库返回的时间转换为几分钟前、几小时前、几天前的形式。

不知道大家的时间格式是什么样子的,我先展示下我这里数据库返回的时间格式

‘2019-05-05T15:52:19Z’

是这个样子的,然后上代码:

在utils文件下创建文件time.js文件

time.js

export default function time(UTCtiem) {
    var T_pos = UTCtiem.indexOf('T');
    var Z_pos = UTCtiem.indexOf('Z');
    var year_month_day = UTCtiem.substr(0, T_pos);
    var hour_minute_second = UTCtiem.substr(T_pos + 1, Z_pos - T_pos - 1);
    var new_datetime = year_month_day + " " + hour_minute_second; 

    var dateTime = new Date(new_datetime);

    var no1new = dateTime.valueOf();

    var year = dateTime.getFullYear();
    var month = dateTime.getMonth() + 1;
    var day = dateTime.getDate();
    var hour = dateTime.getHours();
    var minute = dateTime.getMinutes();
    var second = dateTime.getSeconds();
    var now = new Date();
    var now_new = now.valueOf();  //typescript转换写法

    var milliseconds = 0;
    var timeSpanStr;

    milliseconds = now_new - no1new;

    if (milliseconds <= 1000 * 60 * 1) {
        timeSpanStr = '刚刚';
    }
    else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
        timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前';
    }
    else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) {
        timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前';
    }
    else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) {
        timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前';
    }
    else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year == now.getFullYear()) {
        timeSpanStr = month + '-' + day + ' ' + hour + ':' + minute;
    } else {
        timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
    }
    return timeSpanStr;

}

  

用法:

先需要import,具体看各位的路径

import time from '../utils/time';    //这里请注意自己的路径

let times = time('2019-06-05T15:32:19Z');
console.log('times',times);

代码就是这样!!!