【JavaScript】34_Date对象 ,日期的格式化
8、Date
Date
-
在JS中所有的和时间相关的数据都由Date对象来表示
-
对象的方法:
getFullYear() 获取4位年份
getMonth() 返当前日期的月份(0-11)
getDate() 返回当前是几日
getDay() 返回当前日期是周几(0-6) 0表示周日
…
getTime() 返回当前日期对象的时间戳
时间戳:自1970年1月1日0时0分0秒到当前时间所经历的毫秒数
计算机底层存储时间时,使用都是时间戳
Date.now() 获取当前的时间戳
<script>let d = new Date() // 直接通过new Date()创建时间对象时,它创建的是当前的时间的对象// 可以在Date()的构造函数中,传递一个表示时间的字符串// 字符串的格式:月/日/年 时:分:秒// 年-月-日T时:分:秒d = new Date("2019-12-23T23:34:35")// new Date(年份, 月, 日, 时, 分, 秒, 毫秒)d = new Date(2016, 0, 1, 13, 45, 33)d = new Date()result = d.getFullYear()result = d.getMonth()result = d.getDate()result = d.getDay()result = d.getTime()console.log(result) // 1659088108520 毫秒</script>
9、日期的格式化
toLocaleString()
-
可以将一个日期转换为本地时间格式的字符串
-
参数:
-
描述语言和国家信息的字符串 zh-CN 中文中国 zh-HK 中文香港 en-US 英文美国
-
需要一个对象作为参数,在对象中可以通过对象的属性来对日期的格式进行配置 dateStyle 日期的风格 timeStyle 时间的风格 full long medium short hour12 是否采用12小时值 true false weekday 星期的显示方式 long short narrow
year numeric 2-digit
-
<script>const d = new Date()let result = d.toLocaleDateString() // 将日期转换为本地的字符串result = d.toLocaleTimeString() // 将时间转换为本地的字符串result = d.toLocaleString("zh-CN", {year: "numeric",month: "long",day: "2-digit",weekday: "short",})console.log(result)</script>