js implements date formatting

1. Date object

 Date()是一个构造函数,创建date对象时使用构造函数实例化对象

1. Get the current system time

  var date = new Date();  // new Date(); 获取当前系统时间
  // var date2 = new Date(15554457551111)  //new Date(毫秒数)  代表创建毫秒数对象的日期对象
  console.log(date);  //获取到的是当前时间
  // console.log(typeof date);

2. The original value of the date

获取到的是1970年1月1日至今的毫秒数

 console.log(date.getTime());  // getTime();  日期的原始值  获取到的是1970年1月1日至今的毫秒数

3. Get the year

console.log(date.getFullYear());  // date.getFullYear(); 获取年份

4. Get the month

月份从0开始的所以要加1

 console.log(date.getMonth() + 1); // date.getMonth();  获取月份 月份从0开始的所以要加1

5. Acquisition date

console.log(date.getDate()); // date.getDate();  获取日

6. Get the week

console.log(date.getDay()); //date.getDay(); 获取星期

7. Get hours

 console.log(date.getHours());  //date.getHours(); 获取小时

8. Get minutes

 console.log(date.getMinutes());  // date.getMinutes();  获取分钟

9. Get seconds

console.log(date.getSeconds()); //date.getSeconds();  获取秒

2. Realize date formatting through the method of date object

Realize date formatting renderings

function dateFormat(date) {
    
    
    console.log(showTime(date.getHours()));
    var year = date.getFullYear();                // 年
    var month = showTime(date.getMonth() + 1);        // 月
    var week = showTime(date.getDay());           // 星期
    var day = showTime(date.getDate());          // 日
    var hours = showTime(date.getHours());         // 小时
    var minutes = showTime(date.getMinutes());    // 分钟
    var second = showTime(date.getSeconds());     // 秒
    var str = '';
    str = str + year + '-' + month + '-' + week + '-' + day + '-' + hours + '-' + minutes + '-' + second
    document.write(str);
  }
  var date = new Date();
  dateFormat(date);
    // 封装一个不够两位数就补零的函数
  function showTime(t) {
    
    
    var time
    time = t > 10 ? t : '0' + t
    return time
  }

Effect diagram of date formatting
Date formatting renderings

It contains a function that encapsulates a zero padding if there are not enough two digits

一个不够两位数就补零的函数

 // 封装一个不够两位数就补零的函数
  function showTime(t) {
    
    
    var time
    time = t >= 10 ? t : '0' + t
    return time
  }

Guess you like

Origin blog.csdn.net/weixin_50370865/article/details/127837737