我在JavaScript中轉換日期變量爲特定的格式在JavaScript
var yest_date = "Mon Dec 12 2016 15:33:41 GMT-0800 (Pacific Standard Time)"
我想這個變量「yest_date」要在這個格式此yest_date變量和值。
20161212
有人可以讓我知道如何做到這一點。
我在JavaScript中轉換日期變量爲特定的格式在JavaScript
var yest_date = "Mon Dec 12 2016 15:33:41 GMT-0800 (Pacific Standard Time)"
我想這個變量「yest_date」要在這個格式此yest_date變量和值。
20161212
有人可以讓我知道如何做到這一點。
只需將您的字符串轉換爲實際的日期,然後使用日期getter方法所需的值提取到一個格式化字符串:
let yest_date = "Mon Dec 12 2016 15:33:41 GMT-0800 (Pacific Standard Time)"
let date = new Date(yest_date);
console.log(`${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}`)
Hamms-wat是console.log內的代碼?它的神祕。你可以解釋那裏的$符號 –
它只是一個[模板文字](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) – Hamms
我越來越無效的字符,當我請使用console.log –
你可以做到以下幾點:
const date = new Date('Mon Dec 12 2016 15:33:41 GMT-0800 (Pacific Standard Time)')
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
const formattedDate = `${year}${month}${day}`;
console.log(formattedDate);
我會建議使用moment.js。這是一個非常好的圖書館辦理相關的任何日期時間問題http://momentjs.com/
var yest_date = moment("Mon Dec 12 2016 15:33:41 GMT-0800 (Pacific Standard Time)")
console.log(yest_date.format("YYYYMMDD"))
如果你不想增加額外的庫,然後你可以用經典的字符串連接
let yest_date = new Date("Mon Dec 12 2016 15:33:41 GMT-0800 (Pacific Standard Time)")
console.log(`${yest_date.getFullYear()}${yest_date.getMonth() + 1}${yest_date.getDate()}`)
我收到錯誤當我使用此--->'$ {yest_date.getFullYear()} $ {yest_date.getMonth()+ 1} $ {yest_date.getDate()}' –
什麼是版本和類型是你的瀏覽器?你能提供代碼和完整的錯誤日誌嗎?它適用於我的Chrome。它的工作原理是 –
。謝謝 –
你有一個字符串,只需重新格式化它。 – RobG