当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当前回答
不是一个答案,但这里是我如何得到我在一个变量中需要的日期格式
function setDateZero(date){
return date < 10 ? '0' + date : date;
}
var curr_date = ev.date.getDate();
var curr_month = ev.date.getMonth() + 1;
var curr_year = ev.date.getFullYear();
var thisDate = curr_year+"-"+setDateZero(curr_month)+"-"+setDateZero(curr_date);
希望这能有所帮助!
其他回答
三元运算符解
如果月份或日期小于10,则简单的三元运算符可以在数字之前添加“0”(假设需要在字符串中使用此信息)。
let month = (date.getMonth() < 10) ? "0" + date.getMonth().toString() : date.getMonth();
let day = (date.getDate() < 10) ? "0" + date.getDate().toString() : date.getDate();
如果你能给我点时间的话我想问的是
YYYYMMDD
为了今天,和大家相处:
const dateDocumentID = new Date()
.toISOString()
.substr(0, 10)
.replace(/-/g, '');
("0" + this.getDate()).slice(-2)
对于日期,类似的:
("0" + (this.getMonth() + 1)).slice(-2)
这个月。
date-fns。
import { lightFormat } from 'date-fns';
lightFormat(new Date(), 'dd');
如果你检查的是小于10的,你不需要为它创建一个新函数。只需将变量赋值到括号中,并返回一个三元操作符。
(m = new Date().getMonth() + 1) < 10 ? `0${m}` : `${m}`