原生js如何封装一个时间格式化函数

野性酷女 2022-12-08 05:38 273阅读 0赞

在项目中我们经常遇到一些需求就是如何把时间格式转成一个自己想要的格式,当然啦,你可以使用一些第三方插件比如moment,这是别人已经封装好的,如果你想成为一名有思想的程序员,而不是一位搬运工,你得明白原生js如何自己封装一个时间格式化函数,代码如下:


  1. function formatDate(value, fmt) {
  2. let getDate = new Date(value);
  3. let o = {
  4. 'M+': getDate.getMonth() + 1,
  5. 'd+': getDate.getDate(),
  6. 'h+': getDate.getHours(),
  7. 'm+': getDate.getMinutes(),
  8. 's+': getDate.getSeconds(),
  9. 'q+': Math.floor((getDate.getMonth() + 3) / 3),
  10. 'S': getDate.getMilliseconds()
  11. };
  12. if (/(y+)/.test(fmt)) {
  13. fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length));
  14. }
  15. for (let k in o) {
  16. if (new RegExp('(' + k + ')').test(fmt)) {
  17. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
  18. }
  19. }
  20. return fmt;
  21. }
  22. let d = new Date();
  23. console.log(formatDate(d, 'yyyy-MM-dd')); // 2020-09-18
  24. console.log(formatDate(d, 'yyyy:MM:dd')); // 2020:09:18
  25. console.log(formatDate(d, 'yyyy-MM-dd hh:mm')); // 2020-09-18 17:26

发表评论

表情:
评论列表 (有 0 条评论,273人围观)

还没有评论,来说两句吧...

相关阅读