【问题标题】:Vue JS - How to add zero before month using new Date [duplicate]Vue JS - 如何使用新日期在月份前添加零 [重复]
【发布时间】:2021-09-09 11:15:29
【问题描述】:

我有一个给出日期的函数,唯一的问题是我的日期在 5/31/2021 上显示为这样,但我想让它出现在 05/ 31/2021这是我的代码

<span>{{ dtFormatter(course.updated_at) }}</span>

dtFormatter(d) {
  var dateObj = new Date(d);
  var day = dateObj.getUTCDate();
  var month = dateObj.getUTCMonth() + 1; //months from 1-12
  var year = dateObj.getUTCFullYear();
  return day + "." + month + "." + year;
},

【问题讨论】:

  • new Date().toLocaleDateString('en-UK').replaceAll('/', '.')
  • @HassanImam 给了你一个单行代码来解决你的问题,但是在你的问题中 - 你问的是如何用斜杠'/'来显示它,但是在你的代码中你用点返回'。' - 如果应该使用斜线,只需使用@Hassan 的代码,不要使用replaceAll 函数,如下所示:new Date().toLocaleDateString('en-UK')

标签: javascript vue.js date vuejs2


【解决方案1】:

如果需要,您可以使用padStart 添加前导Zero

day.padStart(2, '0') + '.' + month.padStart(2, '0') + '.' + year

daymonth 应该是一个字符串 btw

【讨论】:

    【解决方案2】:

    如果需要,您可以使用String#slice 添加前导0

    ('0' + day).slice(-2) + '.' + ('0' + month).slice(-2) + '.' + year;
    

    注意:padStart 在 IE 中不起作用。

    【讨论】:

    • 我还没有投反对票,但是你的变量没有在你的答案中声明,所以如果我复制并粘贴它,它将不起作用
    【解决方案3】:

    我看到你已经计算好了这一天。 所以你可以这样做。

    `0${day}`.slice(-2)`

    这将输出 01~09 和 10~31。

    【讨论】:

      【解决方案4】:

      正如@HassanImam 所述,您可以使用单行代码:

      new Date().toLocaleDateString('en-UK')
      

      否则:

      const date = new Date()
      const m = String(date.getMonth() + 1).padStart(2, '0')
      const d = String(date.getDate()).padStart(2, '0')
      const y = String(date.getFullYear())
      
      const formatedDate = [m, d, y].join('/')
      
      console.log(formatedDate)

      【讨论】:

        猜你喜欢
        • 2020-07-26
        • 2021-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-29
        • 1970-01-01
        • 1970-01-01
        • 2011-08-04
        相关资源
        最近更新 更多