目录
3wschool:https://www.w3school.com.cn/js/index.asp
菜鸟教程:https://www.runoob.com/js/js-tutorial.html
创建当前时间对象
见:https://blog.csdn.net/JBY2020/article/details/109864650
要创建一个日期对象,使用new 操作符和Date 构造函数即可,如下所示。
var nowtime = new Date();
创建指定时间的日期对象
通过在Date()中添加参数,创建特定时间对象
- 添加毫秒数:从1970年1月1日00:00:00开始加上这个一个毫秒值的时间
let time1 = new Date(164532542693);
- 添加日期字符串
let time2 = new Date("January 9,2021");
- 添加年/月/日/时/分/秒/毫秒参数:注意:这里的月份是从0开始的
let time3 = new Date(2019, 5, 1, 19, 30, 50);
- 添加字符串时间
let time4 = new Date("2021-5-1");
let time5 = new Date("2021/5/1 18:49:59");
日期时间对象方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let time1 = Date.parse(2021,01,01); // 接收一个日期时间,返回距离1970-01-01 00:00:00的毫秒数
let time2 = Date.parse('1970,01,01'); // 传入字符串时的结果要考虑所在时区,这个结果是-28800000,与0时区刚好相差8小时
let time3 = Date.UTC(2021,0,01); // 接收以逗号隔开的日期时间,返回距1970-01-01 00:00:00的毫秒数,接收的月份为0——11
console.log(time1);
console.log(time2);
console.log(time3);
console.log('Date.now()方法获取当前时间的时间戳:',Date.now()); // 当前时间的时间戳
function datetime() {
let nowtime = new Date(); // 创建日期时间对象
console.log('通过new Date()方法实例化,获取本地时间:',nowtime);
console.log('toDateString()返回的是星期 月 日 年:',nowtime.toDateString());
console.log('toTimeString()返回的是时 分 秒 时区:',nowtime.toTimeString());
console.log('toLocaleDateString()返回的是年/月/日:',nowtime.toLocaleDateString());
console.log('toLocaleTimeString()返回本地时 分 秒:',nowtime.toLocaleTimeString());
console.log('toUTCString()返回对应的UTC时间(也就是国际标准时间[格林威治时间],比北京晚8个小时):',nowtime.toUTCString());
console.log('toLocaleString()返回本地时间:',nowtime.toLocaleString());
console.log('getTime()返回一个毫秒值,时间为此刻到时间零点的时间:',nowtime.getTime());
console.log('getFullYear()返回年:',nowtime.getFullYear());
// getMonth() 返回月 注意:得到的月份是从0开始 要返回当前月需要加1
// getDate() 返回日期
// getHours() 返回小时
// getMinutes() 返回分钟
// getSeconds() 返回秒
// getDay() 返回星期
// getTimezoneOffset() 返回是当前事件与UTC的时区差异 以分钟数表示(考虑夏令营时)
}
datetime();
</script>
</body>
</html>
注意:parse()方法中传入的参数