Javascript 时间格式化输出(JavaScript time formatted output)

描述 ( from 牛客网)

示例1

formatDate(new Date(1409894060000), 'yyyy-MM-dd HH:mm:ss 星期w')
2014-09-05 13:14:20 星期五

——————————————————————————————————————————个人笔记

function formatDate(datetime, format) {  const year = datetime.getFullYear();   const month = datetime.getMonth() + 1;   const date = datetime.getDate();   const hour = datetime.getHours();   const minute = datetime.getMinutes();   const second = datetime.getSeconds();   const day = datetime.getDay();   const dayName = [‘日’, ‘一’, ‘二’, ‘三’, ‘四’, ‘五’, ‘六’][day];   const addZero = (num) => num < 10 ? (“0” + num) : num;   return format.replace(/(yyyy|yy|MM|M|dd|d|HH|H|hh|h|mm|m|ss|s|w)/g, function(match) {     switch(match) {       case “yyyy”:         return year;       case “yy”:         return year % 100;       case “MM”:         return addZero(month);       case “M”:         return month;       case “dd”:         return addZero(date);       case “d”:         return date;       case “HH”:         return addZero(hour);       case “H”:         return hour;       case “hh”:         return addZero(hour % 12);       case “h”:         return hour % 12;       case “mm”:         return addZero(minute);       case “m”:         return minute;       case “ss”:         return addZero(second);       case “s”:         return second;       case “w”:         return dayName;     }   });}

————————

Description (from Niuke)

Example 1

formatDate(new Date(1409894060000), 'yyyy-MM-dd HH:mm:ss 星期w')
2014-09-05 13:14:20 星期五

——————————————————————————————————————————Personal notes

function formatDate(datetime, format) {  const year = datetime.getFullYear();   const month = datetime.getMonth() + 1;   const date = datetime.getDate();   const hour = datetime.getHours();   const minute = datetime.getMinutes();   const second = datetime.getSeconds();   const day = datetime.getDay() ; Const dayname = [‘Day’, ‘one’, ‘two’, ‘three’, ‘four’, ‘five’, ‘six’] [day];   const addZero = (num) => num < 10 ? (“0” + num) : num;   return format. replace(/(yyyy|yy|MM|M|dd|d|HH|H|hh|h|mm|m|ss|s|w)/g, function(match) {     switch(match) {       case “yyyy”:         return year;       case “yy”:         return year % 100;       case “MM” :         return addZero(month);       case “M”:         return month;       case “dd”:         return addZero(date);       case “d”:         return date;       case “HH”:         return addZero(hour);       case “H”:         return hour;       case “hh”:         return addZero(hour % 12);       case “h”:         return hour % 12;       case “mm”:         return addZero(minute);       case “m”:         return minute;       case “ss”:         return addZero(second);       case “s”:         return second;       case “w”:         return dayName;     }   });}