06.全网最全的整理出来常用的时间对象原理及参数方法

139 阅读2分钟

date1028:时间对象

一、时间对象

  1. Date();
  2. 语法形式:var timer = new Date();
  3. 这是当前国际标准时间;

注:千万不要记忆成data。

var time1 = new Date();
console.log(time1);

var time2 = new Date('2022-10-30 10:22:24');
console.log(time2);

二、事件对象的参数

时间对象接收参数有两种格式:

  1. 数字:
  • 自己写入时间的时候,日期如果超过自己设定的这个月的时候,会自动按照标准日期进行计算到几月。
  • eg:
    • var time = new Date( 2022 01 30 10:10:20 );
    • 此时是3月1号或者3月2号(看是平年还是闰年)
  1. 字符串
  • 正常对应01对应一月 02对应二月
// 1.数字传参
// 这个日期就是00对应一月 01对应二月
var timer1 = new Date(1999, 00, 20, 00, 00, 00);
console.log(timer1);

// 2.字符串
// 正常对应01对应一月 02对应二月
var timer = new Date('1999-02-10 00:00:00');
console.log(timer);

01.png

三、格式化时间对象

月份是从0开始的。

  1. 获取每周的第几天:var 变量 = timer.getDay();
  2. 获取每月的第几天:var 变量 = timer.getDate();
  3. 获取年份:var year = timer.getFullYear();
  4. 获取月份:var month = timer.getMonth();
  5. 获取小时:var hours = timer.getHours();
  6. 获取分钟:var minutes = timer.getMinutes();
  7. 获取秒:var seconds = timer.getSeconds();
// 获取当前标准时间
var timer = new Date();
console.log(timer);

// 获取年份year
var year = timer.getFullYear();
console.log(year);

// 获取月份month
var month = timer.getMonth();
console.log(month);

// 获取一个月的第几天
var date = timer.getDate();
console.log(date);

// 获取每一个星期的第几天
var day = timer.getDay();
console.log(day);

// 获取小时hours
 var hours = timer.getHours();
console.log(hours);

// 获取分钟minutes
var minutes = timer.getMinutes();
console.log(minutes);

// 获取秒钟seconds
var seconds = timer.getSeconds();
console.log(seconds);

02.png

四、获取格林尼治时间

1970年1月1日0时0分0秒 到现在的毫秒

语法:

  • var time = new Date();
  • var 变量 = time.getTime();

五、设置时间对象

语法形式:时间对象.setXXXX();

var timer = new Date();
console.log(timer);

// 设置年份并且获取年份
timer.setFullYear(1999);
var years = timer.getFullYear();
console.log(years);

// 设置月份并且获取月份
timer.setMonth(10);
var months = timer.getMonth();
console.log(months);

// 设置日期并且获取
timer.setDate(03);
var dates = timer.getDate();
console.log(dates);

// 设置小时并且打印出来
timer.setHours(14);
var hours = timer.getHours();
console.log(hours);

// 设置分钟并且打印出来
timer.setMinutes(24);
var minutes = timer.getMinutes();
console.log(minutes);

// 设置秒数并且打印出来
timer.setSeconds(36);
var seconds = timer.getSeconds();
console.log(seconds);

console.log(`${years}${months}${dates}${hours}${minutes}${seconds}秒`);

        
// 设置天数  年月日都已经确定了 不可能单独设置周天数
// timer.setday();

// 设置毫秒
// timer.setMilliseconds(1000);
timer.setMilliseconds(999);
console.log(timer.getMilliseconds());

// 设置距离1970年的总毫秒数
timer.setTime(1000);
console.log(timer.getTime());

03.png