日期格式添加 st,nd,rd,th
/**
* 数字前置补零
* @param {number} num - 原始数字
* @param {number} length - 数字长度,如果原始数字长度小于 length,则前面补零,如:util.digit(7, 3) //007
* @returns
*/
let digit = function(num, length){
var str = '';
num = String(num);
length = length || 2;
for(var i = num.length; i < length; i++){
str += '0';
}
return num < Math.pow(10, length) ? str + (num|0) : num;
}
/**
* 转化时间戳或日期对象为日期格式字符
* @param {(object|string))} fmt - 日期格式 - 可以是日期对象,也可以是毫秒数
* @param {format} date - 日期字符格式(默认:yyyy-MM-dd HH:mm:ss),可随意定义,如:yyyy年MM月dd日
* @return {string} 返回的日期字符串
*/
let toDateString = function( time, format ){
//若 null 或空字符,则返回空字符
if(time === null || time === '') return '';
let date = new Date(function(){
if(!time) return;
return isNaN(time) ? time : (typeof time === 'string' ? parseInt(time) : time)
}() || new Date())
,ymd = [
digit(date.getFullYear(), 4)
,digit(date.getMonth() + 1)
,digit(date.getDate())
]
,hms = [
digit(date.getHours())
,digit(date.getMinutes())
,digit(date.getSeconds())
];
format = format || 'yyyy-MM-dd HH:mm:ss';
return format.replace(/yyyy/g, ymd[0])
.replace(/MM/g, ymd[1])
.replace(/dd/g, ymd[2])
.replace(/HH/g, hms[0])
.replace(/mm/g, hms[1])
.replace(/ss/g, hms[2]);
}
/**
* 转换为项目所需要的格式
* @param {string} time - 日期格式 - 可以是日期对象,也可以是毫秒数
* @return {string} 返回的日期字符串
*/
let showDateString = function(time){
let D = toDateString( time, 'dd');
let M = toDateString( time, 'MM');
let Y = toDateString( time, 'yyyy');
// https://zhuanlan.zhihu.com/p/84118627
let strD = parseInt(D);
if( D[0] != 1 ){
switch ( D[1] ) {
case "1":
strD += "st";
break;
case "2":
strD += "nd";
break;
case "3":
strD += "rd";
break;
default:
strD += "th";
break;
}
}else{
strD += "th";
}
let strM = enumsMonth[ parseInt(M) -1 ];
let strY = parseInt(Y);
return `${strM} ${strD}, ${strY}`;
}
showDateString 方法里面
参考
https://zhuanlan.zhihu.com/p/84118627