首先必须要提到的是 Date 对象, 它用来处理时间和日期.
使用 new Date() 语句可创建 Date 对象, 创建出来的时间格式如下(后面提到的标准时间都是指该格式):
Wed Jul 17 2019 13:59:21 GMT+0800 (中国标准时间)
Date 对象有以下几种创建方式:
1. letdate=newDate();2. letdate=newDate(milliseconds);3. letdate=newDate(dateString);4. letdate =newDate(year,month,day,hours,minutes,seconds);
解释:
1. 不传参, 获取的是当前时间;
2. 传时间戳, 时间戳是指格林威治时间 1970 年 01 月 01 日 00 时 00 分 00 秒 (北京时间 1970 年 01 月 01 日 08 时 00 分 00 秒) 起至现在的总秒数, 由 10 位数字组成(毫秒是 13 位), 这里传 10 位 13 位都可以;
3. 传时间的字符串形式, 如 '2019/7/17 14:40:30' 或 '2019-7-17', 这里我试了一下以 '/' 和 '-' 为年月日分隔符都是可以的, 空格和逗号不行, 年月日要完整, 时分秒可不用写全;
4. 传以逗号分隔的时间, 如 2019,7, 17, 14, 40, 30 , 这个试了一下年月是必须的, 其他可以不写全. 注意, month 代表的月份是从 0(1 月)到 11(12 月).
时间戳与日期格式的相互转换:
一, 时间戳转换为标准时间格式
上面已经提到过了, 直接将时间戳作为参数传入 new Date() 即可
let date = new Date(timestamp)
二, 标准时间格式转换为时间戳
这个也很简单, 利用 Date 对象的 getTime() 方法:
let timestamp = new Date().getTime()
这里获得是 13 位时间戳, 即毫秒
三, 标准时间格式转换为指定格式
可以利用 Date 对象的一些方法
- date.getFullYear() // 获取完整的年份
- date.getMonth() // 获取月份(0-11,0 代表 1 月, 用的时候记得加上 1)
- date.getDate() // 获取日(1-31)
- date.getTime() // 获取时间(从 1970.1.1 开始的毫秒数)
- date.getHours() // 获取小时数(0-23)
- date.getMinutes() // 获取分钟数(0-59)
- date.getSeconds() // 获取秒数(0-59)
需要什么样的时间格式, 利用上述方法获得需要的部分再拼接起来.
四, 时间戳转换为指定格式
先将时间戳转换为标准时间格式, 再按三转换为指定格式.
补充: 当我们想处理时间, 例如加一天, 减一天, 要先转换成时间戳再进行计算. 如要获得当前时间的前一小时, 可按如下方法计算:
new Date(new Date().getTime() - 1*60*60*1000)
参考链接:
- https://www.runoob.com/jsref/jsref-obj-date.html
- https://www.jb51.net/article/130303.htm
来源: http://www.bubuko.com/infodetail-3126275.html