0
点赞
收藏
分享

微信扫一扫

Date 对象

爱写作的小土豆 2021-09-25 阅读 58

关于 Date 对象,有几个方法总是记不住或者记混淆的,所以写篇文章整理一下。

Date

在 ECMAScript 中,Date 类型使用自世界标准时间(UTC)1970-1-1 00:00:00 开始经过的毫秒数来保存日期。

// 获取起始时间
const date = new Date(0)
// Thu Jan 01 1970 08:00:00 GMT+0800 (中国标准时间)

创建 Date 两种方式:

// 字符串类型
const date = Date()
console.log(typeof date) // string

// 对象类型(常用)
const date = new Date()
console.log(typeof date) // object

Date Get 方法

下面以 2020 年 12 月 03 日为例:

  • getTime()
    返回 1970 年 1 月 1 日零时至今的毫秒数。

  • getFullYear()
    返回 4 位数的年份(如 2020)。

  • getMonth()
    返回月份,值为 0~11 分别表示 1 月到 12 月。所以一般获取月份都要加一

  • getDate()
    返回一个月的某天,值为 1~31 分别表示 1日到 31 日。

  • getDay()
    返回一周的某天,值为 0~6 分别表示周日、周一到周六。

  • getHours()
    返回小时数,值为 0 ~ 23

  • getMinutes()
    返回分钟数,值为 0 ~ 59

  • getSeconds()
    返回秒数,值为 0 ~ 59

  • getMilliseconds()
    返回毫秒数,值为 0 ~ 999

Date Set 方法

  • setTime()
    以毫秒设置 Date 对象(参数:毫秒数

  • setDate()
    根据本地时间设置 Date 对象中月的某一天(合理参数:1 ~ 31,分别表示 1 ~ 31 日)

  • setMonth()
    根据本地时间设置 Date 对象中月份(参数:0 ~ 11,分别表示 1 ~ 12 月份)

  • setFullYear()
    根据本地时间设置 Date 对象中的年份(参数:4 位数字年份

  • setMilliseconds()
    根据本地时间设置 Date 对象中的毫秒数(参数:0 ~ 999

    超出合理范围,日期对象的时间会相应地更更新。例如 1005,秒数加 1,毫秒数为 5。

  • setSeconds()
    根据本地时间设置 Date 对象中的秒数(参数:0 ~ 59

    超出合理范围,日期对象的时间会相应地更更新。例如 100,分钟数加 1,秒数为 40。

  • setMinutes()
    根据本地时间设置 Date 对象中的秒数(参数:0 ~ 59

    超出合理范围,日期对象的时间会相应地更更新。例如 60,小时数加 1,秒数为 0。

  • setHours()
    根据本地时间设置 Date 对象中的小时数(参数:0 ~ 23

    超出合理范围,日期对象的时间会相应地更更新。例如 24,天数加 1,小时数为 0。

UTC 时间

上述所讲的 Get 和 Set 方法是针对本地时区时间去获取、设置时间的。而 Date 同样提供了获取、设置 UTC 时间,方法如:getUTCMonth()setUTCMonth() 等等。实践过程中,比较少涉及 UTC 时间,所以不展开赘述。可以偷偷点这里去了解。

Date 其他方法

  • Date.now()

    返回自 1970-1-1 00:00:00(UTC)到当前时间的毫秒数。

  • Date.prototype.toString()Date.prototype.toTimeString()Date.prototype.toDateString()

    返回值是以美式英语和人类易读的形式返回日期对象的格式化字符串。该字符串由日期部分(年月日)和时间部分(时分秒及时区)组成。

const date = new Date()

date.toString() // "Thu Dec 03 2020 18:19:17 GMT+0800 (中国标准时间)"
date.toDateString() // "Thu Dec 03 2020"
date.toTimeString() // "18:19:17 GMT+0800 (中国标准时间)"
  • Date.parse()Date.prototype.getTime()Date.prototype.valueOf()
    它们都返回 1970-1-1 00:00:00(UTC)到指定日期的毫秒数。但是它们还是有区别的。
const date = new Date('5/24/2020')
date.setMilliseconds(45) // 设置毫秒数

console.log(date.getTime()) // 1590249600045
console.log(date.valueOf()) // 1590249600045
console.log(Date.parse(date)) // 1590249600000

兼容性

类似 new Date('xxxx/xx/xx xx:xx:xx') 形式的时间对象在 IOS 和 Andriod 系统上都可以被正确的识别,而类似 new Date('xxxx-xx-xx xx:xx:xx') 形式的时间对象在 iOS 系统上无法被正确的识别,需要做一层转化。

const date = new Date('xxxx-xx-xx xx:xx:xx'.replace(/-/g, '/'))

参考

举报

相关推荐

0 条评论