JavaScript Date格式化

本文深入探讨了日期格式化的基本原理与实践,通过详细解释日期格式化过程中的关键概念和模式,帮助开发者掌握如何使用JavaScript高效地对日期进行格式化。文章提供了具体的代码示例,并介绍了日期格式化中常用的模式字母,旨在提升开发者在日期处理方面的技能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. /**
  2. * 对日期进行格式化,
  3. * @param date 要格式化的日期
  4. * @param format 进行格式化的模式字符串
  5. * 支持的模式字母有:
  6. * y:年,
  7. * M:年中的月份(1-12),
  8. * d:月份中的天(1-31),
  9. * h:小时(0-23),
  10. * m:分(0-59),
  11. * s:秒(0-59),
  12. * S:毫秒(0-999),
  13. * q:季度(1-4)
  14. * @return String
  15. * @author yanis.wang@gmail.com
  16. */
  17. function dateFormat(date, format){
  18. if(format===undefined){
  19. format= date;
  20. date=newDate();
  21. }
  22. var map ={
  23. "M": date.getMonth()+1,//月份
  24. "d": date.getDate(),//日
  25. "h": date.getHours(),//小时
  26. "m": date.getMinutes(),//分
  27. "s": date.getSeconds(),//秒
  28. "q":Math.floor((date.getMonth()+3)/3),//季度
  29. "S": date.getMilliseconds()//毫秒
  30. };
  31. format= format.replace(/([yMdhmsqS])+/g,function(all, t){
  32. var v = map[t];
  33. if(v!==undefined){
  34. if(all.length>1){
  35. v='0'+ v;
  36. v= v.substr(v.length-2);
  37. }
  38. return v;
  39. }
  40. elseif(t==='y'){
  41. return(date.getFullYear()+'').substr(4- all.length);
  42. }
  43. return all;
  44. });
  45. return format;
  46. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值