JS获取当前时间,并转成标准格式

总体代码如下,可直接拷贝

// 获取当前的本机时间
//先new一个时间对象
  let now = new Date();
//在通过getTime获取当前时间, 必须加一天
  let nowTime= new Date(now.getTime() + 24 * 60 * 60 * 1000);
//年
  let years = nowTime.getFullYear()
//月份
  let month = nowTime.getMonth() < 10
      ? '0' + (nowTime.getMonth() + 1)
      : nowTime.getMonth() + 1

//日
  let day = nowTime.getDate() < 10
      ? '0' + nowTime.getDate()
      : nowTime.getDate()

//时
  let hours = nowTime.getHours() < 10
      ? '0' + nowTime.getHours()
      : nowTime.getHours()

//分
  let minute = nowTime.getMinutes() < 10
      ? '0' + nowTime.getMinutes()
      : nowTime.getMinutes()

//秒
  let second = nowTime.getSeconds() < 10
      ? '0' + nowTime.getSeconds()
      : nowTime.getSeconds()

  let nowDay = years + "-" + month + '-' + day + ' ' + hours + ':' + minute
// 2023-11-27 19:15

为什么要判断<10 给前面加个0呢. 因为美观一些,如果不加的话,一串时间里看到单位数有点突兀

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值