Thu Aug 22 2013 15:12:00 GMT+0800 (中國標準時間)
此為 Date.toString() 在中文環境下的輸出,非標準 ISO 8601,不可直接用 new Date(str) 可靠解析(各瀏覽器行為不一)。
若已有 Date 實例(如 new Date()、后端傳時間戳),直接格式化:
/**
* 格式化 Date 為 YYYY-MM-DD HH:mm:ss
* @param {Date} date
* @returns {string}
*/
function formatDateTime(date) {
if (!(date instanceof Date) || isNaN(date)) return '';
var pad = function(n) { return n < 10 ? '0' + n : '' + n; };
return date.getFullYear() + '-'
+ pad(date.getMonth() + 1) + '-'
+ pad(date.getDate()) + ' '
+ pad(date.getHours()) + ':'
+ pad(date.getMinutes()) + ':'
+ pad(date.getSeconds());
}
// 用法
var now = new Date(); // 或 new Date(timestamp)
console.log(formatDateTime(now)); // 2024-05-18 14:30:05
function parseChineseDateStr(str) {
// 匹配 "Thu Aug 22 2013 15:12:00 GMT+0800"
var m = str.match(/(\w{3})\s+(\w{3})\s+(\d{1,2})\s+(\d{4})\s+(\d{2}:\d{2}:\d{2})/);
if (!m) return null;
var monthMap = {Jan:0,Feb:1,Mar:2,Apr:3,May:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11};
return new Date(m[4], monthMap[m[2]], m[3], ...m[5].split(':'));
}
警告:依賴語言環境的月份/星期縮寫極不穩健,**強烈建議後端直接傳 ISO 8601 (2013-08-22T15:12:00+08:00) 或時間戳**。
Date.prototype.format = function(fmt) {
var o = {
'M+': this.getMonth() + 1,
'd+': this.getDate(),
'h+': this.getHours(),
'm+': this.getMinutes(),
's+': this.getSeconds(),
'q+': Math.floor((this.getMonth() + 3) / 3),
'S': this.getMilliseconds()
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
for (var k in o) if (new RegExp('(' + k + ')').test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
return fmt;
};
// 用法
new Date().format('yyyy-MM-dd hh:mm:ss.S'); // 2024-05-18 14:30:05.123
new Date().format('yyyy/MM/dd'); // 2024/05/18
new Intl.DateTimeFormat('zh-CN', {
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
hour12: false
}).format(new Date()); // "2024/05/18 14:30:05"
拒絕解析非標準字串,源頭治理日期格式,是前後端協作的專業素養。