我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
[day,,month,,year]= Intl.DateTimeFormat(undefined, { year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(new Date()),year.value+month.value+day.value
or
new Date().toJSON().slice(0,10).replace(/\/|-/g,'')
其他回答
const date = new Date()
console.log(date.toISOString().split('T')[0]) // 2022-12-27
// utc / gmt 0 文档。write('UTC/GMT 0: ' + (new Date()). toisostring()。片(0,19)。替换(/ [^ 0 - 9]/ g, " "));/ / 20150812013509 //客户端本地时间 文档。write('<br/>本地时间:' + (new Date(Date.now()-(new Date()). gettimezoneoffset () * 60000)). toisostring()。片(0,19)。替换(/ [^ 0 - 9]/ g, " "));/ / 20150812113509
Dateformat是一个非常常用的包。
使用方法:
从NPM下载并安装dateformat。在你的模块中需要它:
以格式
然后格式化你的东西:
const myYYYYmmddDate = dateformat(new Date(), 'yyyy-mm-dd');
js有很多有用的日期解析方法。
require (" datejs)
(新的日期()).toString(“名称”)
这个家伙这里=> http://blog.stevenlevithan.com/archives/date-time-format写了一个格式()函数Javascript的日期对象,所以它可以使用熟悉的文字格式。
如果你需要在应用程序的Javascript中使用完整的日期格式,请使用它。否则,如果你想做的是一次性的,那么连接getYear(), getMonth(), getDay()可能是最简单的。