3

js月份和日期前补0的一种简单实现方法

 1 year ago
source link: https://ttzz.eu.org/posts/2022-10-08-js-date-add/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

我的博客创建是通过借助 obisidian 的插件和脚本来生成,创建名称是年月日加时间,国庆期间进行文件名统一重新管理,按【年月日 + 标题】来命名。

js 脚本月日字段生成默认是没有补 0 的,也就是如果 1 位的话显示是这样的 1 月 1 号:1-1,而不是 01-01,这样整体就不统一。

js 日期字段

查了一下资料,找到了一种简单的解决方法。

ES2017 引入了字符串补全长度的功能。如果某个字符串不够指定长度,会在头部或尾部补全。padStart() 用于头部补全,padEnd() 用于尾部补全。  


//用法
  var month = (d.getMonth() + 1).toString().padStart(2, '0'); //需要tosting转换;指头部需要俩位数,没有俩位数就补一个0


//调整后
  var month = (d.getMonth() + 1).toString().padStart(2, '0');

  var day = (d.getDate()).toString().padStart(2, '0');

https://blog.csdn.net/xiaokangna/article/details/122297412

关注一下有惊喜
wxqr.png 公众号
赞赏支持
wechatpay.png 微信打赏 alipay.png 支付宝打赏

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK