
日期格式化在JavaScript的开发中是十分常见的,日期格式化一般情况下是通过format函数来实现的,它可以用来格式化日期并转换的日期格式。本文向大家介绍JavaScript中日期格式化format实现原理及实例。
1、format函数介绍:
用来格式化日期,转换的日期格式。
参数date:要格式化的时间
对Date的扩展,将 Date 转化为指定格式的String 。
//月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q)可以用1-2个占位符, //年(y)可以用1-4个占位符,毫秒(S)只能用1个占位符(是1-3位的数字)。
2、使用format函数格式化日期实例
functiondateFormat(format,date){
if(!format)return'';
date=date||newDate();
letdateMap={
y:date.getFullYear(),
M:date.getMonth()+1,
d:date.getDate(),
h:date.getHours(),
m:date.getMinutes(),
s:date.getSeconds(),
S:date.getMilliseconds()
};
returnformat.replace(/(y+)|(M+)|(d+)|(h+)|(m+)|(s+)|(S+)/g,(a)=>_add0(dateMap[a[0]],a.length))
}
function_add0(time,len){
time=time.toString();
letl=time.length;
returnl<len?'0'.repeat(len-l)+time:time;
}原文来自:https://www.py.cn © 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END

















































暂无评论内容