JavaScript学习笔记—Date
1. 描述
- 在JS中所有的和时间相关的数据都由Date对象来表示
2. 对象的方法
(1)getFullYear() 返回当前日期的年份(4位)
(2)getMonth() 返回当前日期的月份(0-11)
(3)getDate() 返回当前日期的几日
(4)getDay() 返回当前日期是周几(0-6)0表示周日
(4)getTime() 返回当前日期对象的时间戳(自1970年1月1日0时0分0秒到当前时间所经历的毫秒数)
(5)Date.now() 获取当前时间戳
let d = new Date();
// 可以在Date()的构造函数中,传递一个表示时间的字符串
// 时间字符串格式:月/日/年 时:分:秒
// 年-月-日T时:分:秒 -> 小于10的前面补0
d = new Date("1/26/2023 13:39:20");
d = new Date("2023-01-26T13:39:20");
// new Date(年,月,日,时,分,秒,毫秒)
d = new Date(2023,0,26,13,39,20);
// new Date(xxx) xxx: 时间戳
d = new Date(1674711560000);
3. 日期格式化
const d = new Date();
let result = d.toLocaleDateString(); // 2023/1/26 将日期转换为本地的字符串
result = d.toLocaleTimeString(); // 14:04:33 将时间转换为本地的字符串
result = d.toLocaleString(); // 2023/1/26 14:04:33 将日期时间转换为本地的字符串
/*
toLocaleString()
- 可以将一个日期转换为本地时间格式的字符串
- 参数:
1. 描述语言和国家信息的字符串
zh-CN 中文中国
zh-HK 中文香港
en-US 英文美国
2. 需要一个对象作为参数,在对象中可以通过对象的属性来对日期的格式进行配置
dateStyle 日期风格
full 2023年1月26日星期四
long 2023年1月26日
medium 2023年1月26日
short 2023/1/26
timeStyle 时间风格
full 中国标准时间 16:22:00
long GMT+8 16:22:00
medium 16:22:00
short 16:22
hour12 是否采用12小时制
true 2023/1/26 下午4:29:39
false 2023/1/26 16:29:13
weekday 星期的显示方式
long 星期四
short 周四
narrow 四
*/
result = d.toLocaleString("zh-CN", {dateStyle: "short", timeStyle: "medium"}); // 2023/1/26 16:37:23