Skip to content

Instantly share code, notes, and snippets.

@52cik
Created March 13, 2016 11:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 52cik/9fb67f8d18c982cff83f to your computer and use it in GitHub Desktop.
Save 52cik/9fb67f8d18c982cff83f to your computer and use it in GitHub Desktop.
js 日期格式化
function formatDate(date, formater) {
date = new Date(date);
var week = '日一二三四五六';
var data = {
'y': date.getFullYear(), // 年
'M': date.getMonth() + 1, // 月
'd': date.getDate(), // 日
'E': week.charAt(date.getDay()),
'h': date.getHours(), // 小时
'm': date.getMinutes(), // 分
's': date.getSeconds(), // 秒
'q': Math.floor((date.getMonth() + 3) / 3), // 季度
'S': date.getMilliseconds() // 毫秒
};
return formater.replace(/(([yMdhmsqSE])+)/g, function (m, key, chr) {
if (chr === 'y') {
return (data[chr] + '').substr(4 - key.length);
} else if (chr === 'E') {
return (['周', '星期'][key.length - 2] || '') + data[chr];
}
return key === chr ? data[chr] : ('00' + data[chr]).substr(('' + data[chr]).length);
});
}
console.log(formatDate(new Date(), 'yyyy-M-d E h:m:s.S')); // => 2016-3-13 日 19:18:46.63
console.log(formatDate(new Date(), 'yyyy-MM-dd EE hh:mm:ss.S')); // => 2016-03-13 周日 19:18:46.65
console.log(formatDate(new Date('2016/1/1'), 'yyyy-MM-dd EE hh:mm:ss')); // => 2016-01-01 周五 00:00:00
console.log(formatDate('2016/1/1 08:08:01', 'yyyy-MM-dd EEE hh:mm:ss')); // => 2016-01-01 星期五 08:08:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment