我有下面的代碼採取日期:Date類轉換
var d = new Date();
var n = d.toString();
與輸出:孫二零一七年十月十五日12時09分42秒GMT + 0300(EEST) 但我需要將其轉換爲下一格式: 2017-10-15 12:09:42 +0300
這可能與日期類方法,或者我應該使用一些正則表達式的輸出字符串,格式化?
我有下面的代碼採取日期:Date類轉換
var d = new Date();
var n = d.toString();
與輸出:孫二零一七年十月十五日12時09分42秒GMT + 0300(EEST) 但我需要將其轉換爲下一格式: 2017-10-15 12:09:42 +0300
這可能與日期類方法,或者我應該使用一些正則表達式的輸出字符串,格式化?
這可以通過一個名爲moment.js
的庫輕鬆完成,請通過文檔進行任何額外的調整,請查看下面的示例並讓我知道這是否對您有幫助!
var moment_d = moment().format('YYYY-MM-DD hh:mm:ss ZZ');
console.log(moment_d);
<script src="https://momentjs.com/downloads/moment.min.js"></script>
中沒有任何JavaScript的Date對象將可以方便地得到你所需要的輸出。另一方面,moment.js是一個80+ KB的野獸,在大多數情況下顯然是過度殺傷力。
如果你尋找它們,那裏有一些輕量級的解決方案。
或者,你可以解析.toISOString()
的輸出,它可以讓你遠達'2017-10-15T12:09:42.301Z'
,並將它與.getTimezoneOffset()
結合起來,它返回從UTC(積極向西)的分鐘數。
JS日期時間操作庫很大,我建議你自己滾動,如果你只需要覆蓋一些情況。
function formatDate(date) {
date = date || new Date(); // default to current time if parameter is not supplied
let formattedDate = date.toISOString(); // returns 2000-01-04T00:00:00.000Z
const timezone = date.getTimezoneOffset()/0.6; // returns timezone in minutes, so dividing by 0.6 gives us e.g -100 for -1hr
const timezoneString = String(timezone) // padStart is a method on String
.padStart(4, '0') // add zeroes to the beginning if only 1 digits
.replace(/^(-|\+)(\d{3})$/, '$10$2') // add a zero between a - or + and the first digit if needed
.replace(/^\d/, '+$&'); // add a plus to the beginning if zero timezone difference
formattedDate = formattedDate
.replace('T', ' ') // replace the T with a space
.replace(/\.\d{3}Z/, '') // remove the Z and milliseconds
+ ' ' // add a space between timezone and time
+ timezoneString; // append timezone
return formattedDate;
}
console.log(formatDate(new Date(2016, 08, 24, 9, 20, 0)));
console.log(formatDate(new Date(2015, 03, 9, 18, 4, 30)));
console.log(formatDate(new Date(1999, 12, 4)));
console.log(formatDate(new Date(1999, 01, 4)));
console.log('----');
MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date – dfsq