当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:

对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?


当前回答

使用Moment.js可以这样做:

moment(new Date(2017, 1, 1)).format('DD') // day
moment(new Date(2017, 1, 1)).format('MM') // month

其他回答

三元运算符解

如果月份或日期小于10,则简单的三元运算符可以在数字之前添加“0”(假设需要在字符串中使用此信息)。

let month = (date.getMonth() < 10) ? "0" + date.getMonth().toString() : date.getMonth();
let day = (date.getDate() < 10) ? "0" + date.getDate().toString() : date.getDate();

只是另一个例子,几乎是一行。

var date = new date (); console.log((date.getMonth() < 9 ?'0': ")+ (date.getMonth()+1));

function monthFormated() {
  var date = new Date(),
      month = date.getMonth();
  return month+1 < 10 ? ("0" + month) : month;
}

怎么容易?

new Date().toLocaleString("en-US", { day: "2-digit" })

其他选项是可用的:

工作日 一年 月

更多信息请点击这里。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString#using_options

date-fns。

import { lightFormat } from 'date-fns';
lightFormat(new Date(), 'dd');