Advertisement

js获取当前时间(年月日、小时分钟秒、星期几)

阅读量:
复制代码
   var weekday = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]

    
     function formatTime(time, fmt) {
    
        if (!time) return '';
    
          else {
    
             const date = new Date(time);
    
             const o = {
    
                 'M+': date.getMonth() + 1,
    
                 'd+': date.getDate(),
    
                 'H+': date.getHours(),
    
                 'm+': date.getMinutes(),
    
                 's+': date.getSeconds(),
    
                 'q+': Math.floor((date.getMonth() + 3) / 3),
    
                 S: date.getMilliseconds(),
    
             };
    
             if (/(y+)/.test(fmt))
    
                 fmt = fmt.replace(
    
                     RegExp.$1,
    
                     (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    
                 );
    
             for (const 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;
    
         }
    
     }
    
  
    
     var dateDay = formatTime(new Date(), 'HH: mm: ss');
    
     console.log(dateDay);    // 13: 46: 46
    
     var dateYear = formatTime(new Date(), 'yyyy-MM-dd');
    
     console.log(dateYear);   // 2021-08-27
    
     var dateWeek = weekday[new Date().getDay()];
    
     console.log(dateWeek);   // 周五

全部评论 (0)

还没有任何评论哟~