当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当前回答
只是另一个例子,几乎是一行。
var date = new date (); console.log((date.getMonth() < 9 ?'0': ")+ (date.getMonth()+1));
其他回答
const today = new Date().toISOString()
const fullDate = today.split('T')[0];
console.log(fullDate) //prints YYYY-MM-DD
我建议您使用另一个名为Moment https://momentjs.com/的库
这样你就可以直接格式化日期,而不需要做额外的工作
const date = moment().format('YYYY-MM-DD')
// date: '2020-01-04'
确保你也导入了moment,以便能够使用它。
yarn add moment
# to add the dependency
import moment from 'moment'
// import this at the top of the file you want to use it in
D项是正确答案
三元运算符解
如果月份或日期小于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 net = require('net')
function zeroFill(i) {
return (i < 10 ? '0' : '') + i
}
function now () {
var d = new Date()
return d.getFullYear() + '-'
+ zeroFill(d.getMonth() + 1) + '-'
+ zeroFill(d.getDate()) + ' '
+ zeroFill(d.getHours()) + ':'
+ zeroFill(d.getMinutes())
}
var server = net.createServer(function (socket) {
socket.end(now() + '\n')
})
server.listen(Number(process.argv[2]))
怎么容易?
new Date().toLocaleString("en-US", { day: "2-digit" })
其他选项是可用的:
工作日 一年 月
更多信息请点击这里。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString#using_options