距离当前相隔时间(刚刚、分钟前、YYYY-MM-DD)

310 阅读1分钟

使用场景

1、自动保存功能:保存距离当前多长时间

 2、评论显示功能,显示评论时间和当前时间的间隔

代码

/** 时间转换@params 时间戳 */
import moment from 'moment';

// 补0 const zeroize = (num: number) => { return num < 10 ? '0' + num : num; };

const formatTime = (time?: number | string) => {    
if (!time) {        
   return null;  
}   
// 拿到当前的时间戳(毫秒) -- 转换为秒   
const currentTime = new Date();   
const currentTimestamp = new Date().getTime() / 1000;   
// 传进来的时间戳(毫秒)   
const t = new Date(time);  
const oldTimestamp = t.getTime() / 1000;   
// 年   
const oldY = t.getFullYear(); 
// 月  
const oldM = t.getMonth() + 1; 
// 日  
const oldD = t.getDate();   
// 时   
const oldH = t.getHours();  
// 分  
const oldi = t.getMinutes(); 
// 相隔多少秒    
const timestampDiff = currentTimestamp - oldTimestamp;  
// 一分钟以内   
if (timestampDiff < 60) {  
   return '刚刚'; 
 }   
// 一小时以内 
if (timestampDiff < 60 * 60) {     
   return Math.floor(timestampDiff / 60) + '分钟前'; 
 }   
 // 今天的时间 
if (oldY === currentTime.getFullYear() && oldM === currentTime.getMonth() + 1 && oldD === currentTime.getDate()) {       
   return `${zeroize(oldH)}:${zeroize(oldi)}`;  
 }  
// 剩下的,就是昨天及以前的数据 
return moment(time).format('YYYY-MM-DD');
};
export default formatTime;