我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
很好,很简单:
var date = new Date();
var yyyy = date.getFullYear();
var mm = date.getMonth() + 1; // getMonth() is zero-based
if (mm < 10) mm='0'+mm;
var dd = date.getDate();
if (dd < 10) dd='0'+dd;
/*date.yyyymmdd();*/
console.log('test - '+yyyy+'-'+mm+'-'+dd);
其他回答
有些日期=新日期(); =某物。 游戏机。log (dateFormated);
对公认答案的一点变化:
函数getDate_yyyymmdd() { const date = new date (); const yyyy = date.getFullYear(); const mm = String(date.getMonth() + 1).padStart(2,'0'); const dd = String(date.getDate()).padStart(2,'0'); 返回“$ {yyyy} $ {mm} $ {dd} ' } console.log (getDate_yyyymmdd ())
Dateformat是一个非常常用的包。
使用方法:
从NPM下载并安装dateformat。在你的模块中需要它:
以格式
然后格式化你的东西:
const myYYYYmmddDate = dateformat(new Date(), 'yyyy-mm-dd');
纯JS (ES5)解决方案,没有任何可能的日期跳转问题,由date . toisostring()打印UTC:
var now = new Date();
var todayUTC = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
return todayUTC.toISOString().slice(0, 10).replace(/-/g, '');
这是为了回应@weberste对@Pierre Guilbert的回答的评论。
const date = new Date()
console.log(date.toISOString().split('T')[0]) // 2022-12-27