Date
Date - JavaScript
1 Date介绍
- 在JS中所有的和时间相关的数据都由Date对象来表示
创建Date对象
let d = new Date() // 直接通过new Date()创建时间对象时,它创建的是当前的时间的对象
console.log(d)

2 常用方法介绍
getFullYear()获取4位年份getMonth()返当前日期的月份(0-11)getDate()返回当前是几日getDay()返回当前日期是周几(0-6) 0表示周日getHours返回当前小时getMinutes返回当前分钟getSeconds返回秒getTime()返回当前日期对象的时间戳- 时间戳:自1970年1月1日0时0分0秒到当前时间所经历的毫秒数
- 计算机底层存储时间时,使用都是时间戳
- Date.now() 获取当前的时间戳
3 创建指定日期的Date对象
方法一
// 月/日/年 时:分:秒
let d = new Date("12/20/1998")
console.log(d)

方法二
// 年-月-日T时:分:秒
let d = new Date("2020-12-30")
console.log(d)

方法三
推荐使用这种方式创建
月从0开始记数
至少需要传两个参数
// new Date(年份, 月, 日, 时, 分, 秒, 毫秒)
let d = new Date(2020, 0, 1, 13, 45, 33)
console.log(d)

方法四
使用时间戳
let timeNow = new Date().getTime()
console.log(timeNow) // 获取当前的时间戳
let d = new Date(timeNow)
console.log(d)

4 日期的格式化
// 将日期转换为本地的字符串
console.log(d.toLocaleDateString())
// 将时间转换为本地的字符串
console.log(d.toLocaleTimeString())
// 将时间日期都转
console.log(d.toLocaleString())

toLocaleString()
-
可以将一个日期转换为本地时间格式的字符串
-
参数
-
描述语言和国家信息的字符串
- zh-CN 中文中国
- zh-HK 中文香港
- en-US 英文美国
-
需要一个对象作为参数,在对象中可以通过对象的属性来对日期的格式进行配置
配置文档
- dateStyle 日期的风格
- timeStyle 时间的风格
- full
- long
- medium
- short
- hour12 是否采用12小时值
- true
- false
- weekday 星期的显示方式
"long"(e.g.,Thursday)"short"(e.g.,Thu)"narrow"(e.g.,T). Two weekdays may have the same narrow style for some locales (e.g.Tuesday’s narrow style is alsoT).
- year
"numeric"(e.g.,2012)"2-digit"(e.g.,12)
- month
"numeric"(e.g.,3)"2-digit"(e.g.,03)"long"(e.g.,March)"short"(e.g.,Mar)"narrow"(e.g.,M). Two months may have the same narrow style for some locales (e.g.May’s narrow style is alsoM).
- day
"numeric"(e.g.,1)"2-digit"(e.g.,01)
-




















