React combat the database will return time into a few minutes ago, a few hours ago, in the form of a few days ago.

React to combat the database return time is converted into the first few minutes, a few hours ago, in the form of a few days ago.

I do not know what it was like time format, the next I'm here to show my database returns the time format

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

It is like this, then on the code:

Create a file time.js file in the file utils

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;

}

  

usage:

First need to import, you look at the specific path

import time from '../utils/time'; // Note here that their path 

the let Times Time = ( '2019-06-05T15: 32: 19Z'); 

the console.log ( 'Times', Times);

 

The code is so! ! !

Guess you like

Origin www.cnblogs.com/Yu-Shuai/p/10980173.html