【笔记】JS的日期和时间

前言

JS的日期和时间学习笔记

获取当前时间的日期对象

1
let now = new Date();

获取指定时间的日期对象

指定字符串

1
let t = new Date("2012-12-12 12:12:12");

指定时间戳

<timestamp>:时间戳

1
let t = new Date(<timestamp>);

指定年月

1
let t = new Date(2012, 12);

指定年月日

1
let t = new Date(2012, 12, 12);

指定年月日时

1
let t = new Date(2012, 12, 12, 12);

指定年月日时分

1
let t = new Date(2012, 12, 12, 12, 12);

指定年月日时分秒

1
let t = new Date(2012, 12, 12, 12, 12, 12);

指定年月日时分秒毫秒

1
let t = new Date(2012, 12, 12, 12, 12, 12, 12);

时间戳

获取当前时间的时间戳

1
let timestamp = Date.now();

获取指定时间的时间戳

通过日期对象获取时间戳

1
2
let now = new Date();
Date.parse(now);

通过日期格式字符串获取时间戳

1
Date.parse("2012/12/12 12:12");

时间戳与日期对象转换

将日期对象转换为时间戳

1
2
let now = new Date();
now.getTime();

将时间戳转换为日期对象

<timestamp>:时间戳

1
new Date(<timestamp>);

日期和时间对象转换为当前地区时间格式

转换为当前地区的日期

1
now.toLocaleDateString();

转换为当前地区的时间

1
now.toLocaleTimeString();

日期和时间对象转换为其他地区时间格式

格林威治时间

1
now.toGMTString();

全球标准时间(UTC)

1
now.toUTCString();

日期和时间对象转换为字符串

转换日期为字符串

1
now.toDateString();

转换时间为字符串

1
now.toTimeString();

强制转换为字符串

1
now.toString();

获取日期对象中的属性值

获取年

1
now.getFullYear()

获取月

  • 月份是从0开始
1
now.getMonth();

获取月中日

1
now.getDate();

获取星期中日

1
now.getDay();

获取时

1
now.getHours();

获取分

1
now.getMinutes();

获取秒

1
now.getSeconds();

获取毫秒

1
now.getMilliseconds();

完成

参考文献

稀土掘金——老陌笔记
CSDN——彭世瑜