本文详细解析JavaScript中new Date()构造函数的多种参数格式,包括字符串分隔符限制、月份从0开始计数的特性以及时间戳输入方式。同时介绍获取年月日、时分秒、星期及天数的常用方法,并提供国标时间与时间戳相互转换的实用代码示例,帮助开发者准确处理日期时间数据。
JavaScript中new Date()对象的各类方法使用说明
1. new Date() 构造函数参数详解
a. 返回结果为国际标准时间格式;b. 不传入参数时,直接返回当前系统时间;c. 传入参数时,返回对应时间的国际标准时间;d. 日期字符串中的分隔符支持英文逗号(,)、连字符(-)、斜杠(/)、点号(.)、星号(*)、等号(=)以及感叹号(!)、at符号(@)、井号(#)、人民币符号(¥)、百分号(%)、和号(&),但不支持波浪号(~)、中间点(·)、反引号(`)、脱字符(^)和加号(+),也不支持中文逗号(,)和句号(。)。
new Date()
Sun Aug 21 2022 15:22:09 GMT+0800 (中国标准时间)
new Date("2022-01-01")
Sat Jan 01 2022 08:00:00 GMT+0800 (中国标准时间)
new Date("2022/01/01")
Sat Jan 01 2022 00:00:00 GMT+0800 (中国标准时间)
new Date("2022.01.01")
Sat Jan 01 2022 00:00:00 GMT+0800 (中国标准时间)
new Date("2022*01*01")
Sat Jan 01 2022 00:00:00 GMT+0800 (中国标准时间)
new Date("Sat Jan 2022")
Sat Jan 01 2022 00:00:00 GMT+0800 (中国标准时间) 注1:所有英文括号必须为左括号或成对出现,若出现两个右括号则无法被正确识别。
new Date("2022(01)01")
Sat Jan 01 2022 00:00:00 GMT+0800 (中国标准时间)
new Date("2022(01(01")
Sat Jan 01 2022 00:00:00 GMT+0800 (中国标准时间)
new Date("2022)01)01")
Invalid Date // 无效的时间注2:也可以使用六个参数分别表示年、月、日、时、分、秒。需注意第二个参数代表月份,且值需减一,例如传入1实际表示二月;若第三个参数为0,则代表上个月的最后一天。
new Date("2022","01",0,11,12,20)
Mon Jan 31 2022 11:12:20 GMT+0800 (中国标准时间)注3:当入参为时间戳时,返回对应的国际标准时间。
new Date(1661051533000)
//Sun Aug 21 2022 11:12:13 GMT+0800 (中国标准时间)2. 常用方法篇
查询指定月份包含的天数
//2022年一月份的天数
new Date("2022","01",0).getDate() // 31日常开发中常用方法
入参日期的 时间戳
new Date("2022-08-21 11:12:13").getTime() // 1661051533000
入参日期的 星期(注:日:0 ,一:1,二:2,三:3,四:4,五:5,六:6)
new Date("2022-08-21 11:12:13").getDay() // 0
入参日期的 年
new Date("2022-08-21 11:12:13").getFullYear() // 2022
入参日期的 月 -1
new Date("2022-08-21 11:12:13").getMonth() // 7
入参日期的 日
new Date("2022-08-21 11:12:13").getDate() // 21
入参日期的 时
new Date("2022-08-21 11:12:13").getHours() // 11
入参日期的 分
new Date("2022-08-21 11:12:13").getMinutes() // 12
入参日期的 秒
new Date("2022-08-21 11:12:13").getSeconds() // 13
入参日期的 毫秒 (注:最大为999)
new Date("2022-08-21 11:12:13:999").getMilliseconds() //999
入参日期距离1900年的年数
new Date("2022-08-21 11:12:13").getYear() // 1223. 国际标准时间、时间戳、年月日时分秒之间的转换
//vue js 文件
handlerZero(param){
param= param<10?('0'+param):param
},
// 国标时间 转 年月日 时分秒
formatDateTime(date) {
let y = date.getFullYear()
let m = date.getMonth()+1
let d = date.getDate()
let h = date.getHours()
let h = date.getHours()
let mi = date.getMinutes()
let ss = date.getSeconds()
return y+this.handlerZero(m)+this.handlerZero(d)+this.handlerZero(h)+this.handlerZero(mi)+this.handlerZero(ss)
},
// 时间戳转年月日 时分秒
formatDateTime2(date) {
let datee = new Date(date)
return this.formatDateTime(datee)
},
// 年月日 转 时间戳
formatDateTime3(date) {
let y = date.substring(0,4)
let m = date.substring(4,6)
let d = date.substring(6,8)
let str = y+'-'+m+'-'+d
return new Date(str).getTime()
}至此,关于JS中new Date()各方法用法的介绍已结束,更多相关内容请搜索本站历史文章或继续浏览后续文章,希望大家今后多多支持本站!