我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
最短的
.toJSON().slice(0,10).split`-`.join``;
let d = new Date(); let s = d.toJSON().slice(0,10).split ' - ' .join '; console.log(年代);
其他回答
对公认答案的一点变化:
函数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 ())
new Date('Jun 5 2016').
toLocaleString('en-us', {year: 'numeric', month: '2-digit', day: '2-digit'}).
replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');
// => '2016-06-05'
如果你不需要一个纯JS的解决方案,你可以使用jQuery UI来做这样的工作:
$.datepicker.formatDate('yymmdd', new Date());
我通常不喜欢导入太多的库。但是jQuery UI非常有用,你可能会在项目的其他地方用到它。
更多示例请访问http://api.jqueryui.com/datepicker/
我写了一个简单的函数,它可以将Date对象转换为具有日期号、月份号(带零填充)和年份号的可定制顺序的String。您可以将它与您喜欢的任何分隔符一起使用,或者将此参数保留为空以在输出中不显示分隔符。请看一看。
function dateToString(date, $1, $2, $3, separator='') { const dateObj = { date: String(date.getDate()).padStart(2, '0'), month: String(date.getMonth() + 1).padStart(2, '0'), year: date.getFullYear() }; return dateObj[$1] + separator + dateObj[$2] + separator + dateObj[$3]; } const date = new Date(); const dateString1 = dateToString(date, 'year', 'month', 'date'); console.log(dateString1); // Manipulate arguments order to get output you want const dateString2 = dateToString(date, 'date', 'month', 'year', '-'); console.log(dateString2);
yyyymmdd=x=>(f=x=>(x<10&&'0')+x,x.getFullYear()+f(x.getMonth()+1)+f(x.getDate())); 警报(年年月日(新日期));