UNPKG

redscorpion-utils

Version:

A good JavaScript tools

1 lines 1.47 kB
const NORM_DATE_PATTERN='yyyy-MM-dd';const NORM_DATETIME_PATTERN='yyyy-MM-dd HH:mm:ss';export const format=(date=new Date(),fmt=NORM_DATETIME_PATTERN)=>{if(typeof date==='string'){date=date.replace(/-/g,'/')}date=new Date(date);const o={'M+':date.getMonth()+1,'d+':date.getDate(),'H+':date.getHours(),'m+':date.getMinutes(),'s+':date.getSeconds(),'q+':Math.floor((date.getMonth()+3)/3),'S+':date.getMilliseconds(),w:date.getDay()};if((/(y+)/).test(fmt)){fmt=fmt.replace(RegExp.$1,`${date.getFullYear()}`.substr(4-RegExp.$1.length))}for(const key in o){if(new RegExp(`(${ key })`).test(fmt)){fmt=fmt.replace(RegExp.$1,RegExp.$1.length===1?o[key]:`00${o[key]}`.substr(`${o[key]}`.length))}}return fmt};export const formatDateTime=(date=new Date())=>format(date,NORM_DATETIME_PATTERN);export const formatDate=(date=new Date())=>format(date,NORM_DATE_PATTERN);export const formatNow=(fmt=NORM_DATETIME_PATTERN)=>format(new Date(),fmt);export const timeAgo=(time,onlyDate=true)=>{let stamp=new Date().getTime()-new Date(time).getTime();if(stamp>1000*60*60*24*31){stamp=new Date(time);if(onlyDate){return format(stamp,NORM_DATE_PATTERN)}return format(stamp,NORM_DATETIME_PATTERN)}if(stamp>=1000*60*60*24){return `${stamp/1000/60/60/24|0}天前`}if(stamp>=1000*60*60){return `${stamp/1000/60/60|0}小时前`}if(stamp>=1000*60*3){return `${stamp/1000/60|0}分钟前`}if(stamp<0){return '未来'}return '刚刚'};export default{format,formatDateTime,formatDate,formatNow,timeAgo};