在项目中我们经常遇到一些需求就是如何把时间格式转成一个自己想要的格式,当然啦,你可以使用一些第三方插件比如moment,这是别人已经封装好的,如果你想成为一名有思想的程序员,而不是一位搬运工,你得明白原生js如何自己封装一个时间格式化函数,代码如下:
function formatDate(value, fmt) { let getDate = new Date(value); let o = { 'M+'
: getDate.getMonth() + 1, 'd+': getDate.getDate(), 'h+': getDate.getHours(),
'm+': getDate.getMinutes(), 's+': getDate.getSeconds(), 'q+': Math.floor((
getDate.getMonth() + 3) / 3), 'S': getDate.getMilliseconds() }; if (/(y+)/.test(
fmt)) { fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 -
RegExp.$1.length)); } for (let k in o) { if (new RegExp('(' + k + ')').test(fmt)
) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[
k]).substr(('' + o[k]).length))); } } return fmt; } let d = new Date(); console.
log(formatDate(d, 'yyyy-MM-dd')); // 2020-09-18 console.log(formatDate(d,
'yyyy:MM:dd')); // 2020:09:18 console.log(formatDate(d, 'yyyy-MM-dd hh:mm'));
// 2020-09-18 17:26

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信