JS中 new Date() 各方法的用法说明

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JS中 new Date() 各方法的用法说明

Xie_bro777   2022-12-19 我要评论

JS中 new Date() 各方法的用法

1.new Date() 参数篇

a.返回类型为国标时间,
b.无参数时可以直接返回输出时的时间,
c.有参数时则返回对应时间的国标时间,
d.日期中间的符号可以为,(英文逗号) - / . * = !@ # ¥ % & ,不可为~ · ` ^ + ,(中文逗号) 。

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() 		// 122

3.国标时间、时间戳、年月日 时分秒的转换

//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()
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们