1. 字符串使用正则替换的技巧

      1. function formatDate(oldDate, fmt) {
      2. let date = null;
      3. if (typeof oldDate === 'string' || typeof oldDate === 'number') {
      4. date = new Date(oldDate);
      5. } else {
      6. date = oldDate;
      7. }
      8. if (/(y+)/.test(fmt)) {
      9. fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').slice(4 - RegExp.$1.length))
      10. }
      11. let o = {
      12. "M+": date.getMonth() + 1,
      13. 'd+': date.getDate(),
      14. 'h+': date.getHours(),
      15. 'm+': date.getMinutes(),
      16. 's+': date.getSeconds(),
      17. }
      18. function padLeftZero(str) {
      19. return ("00" + str).substr(str.length);
      20. }
      21. for (let k in o) {
      22. if (new RegExp(`(${k})`).test(fmt)) {
      23. let str = o[k] + '';
      24. fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str));
      25. }
      26. }
      27. return fmt;
      28. }
    2. 开发常用的库,dayjs

    3. tinydate, A tiny (349B) reusable date formatter. Extremely fast!
    4. You-Dont-Need-Momentjs