JavaScript实现日期时间转时间戳

Dulcea ·
更新时间:2024-09-20
· 709 次阅读

目录

1、date.getTime()

2、date.valueOf()

3、Date.parse(date)

4.时间戳转年月日时分秒

5.当前时间往前推30天、7天、3天

6.获取最近七天日期

1、date.getTime()

2、date.valueOf()

3、Date.parse(date)

第一、第二种:会精确到毫秒

第三种:只能精确到秒,毫秒用000替代

注意:获取到的时间戳除以1000就可获得Unix时间戳,就可传值给后台得到。

4.时间戳转年月日时分秒 // 时间戳转年月日 getYMDHMS(timestamp) { var date = new Date(); //时间戳为10位需*1000,时间戳为13位的话不需乘1000 var Y = date.getFullYear() + '-'; var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '; var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'; var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'; var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()); var strDate = Y + M + D + h + m + s; return strDate; }, 5.当前时间往前推30天、7天、3天 this.getData(-30);//前推30天 this.getData(-7);//前推7天 this.getData(-3);//前推3天 getData(day){ var today=new Date() var targetday=today.getTime() +1000*60*60*24* day today.setTime(targetday) var tYear=today.getFullYear() var tMonth=today.getMonth() var tDate=today.getDate() tMonth=this.doHandMonth(tMonth+1) tDate=this.doHandMonth(tDate) return tYear +"-" + tMonth+"-"+tDate } doHandMonth(month){ var m=month if(month.toString().length==1){ m="0"+month } return m } 6.获取最近七天日期 //返回最近七天的日期 getday2() { let days = []; for(let i=0; i<=24*6;i+=24){//今天加上前6天 let dateItem=new Date(Date.getTime() - i * 60 * 60 * 1000);//使用当天时间戳减去以前的时间毫秒(小时*分*秒*毫秒) let y = dateItem.getFullYear();//获取年份 let m = dateItem.getMonth() + 1;//获取月份js月份从0开始,需要+1 let d= dateItem.getDate();//获取日期 m = this.addDate0(m);//给为单数的月份补零 d = this.addDate0(d);//给为单数的日期补零 let valueItem= y + '-' + m + '-' + d;//组合 days.push(valueItem);//添加至数组 } console.log('最近七天日期:',days); return days; }, //给日期加0 addDate0(time) { if (time.toString().length == 1) { time = '0' + time.toString(); } return time; },

到此这篇关于JavaScript 实现日期时间转时间戳的文章就介绍到这了,更多相关JavaScript 时间转时间内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



日期时间 时间戳 JavaScript

需要 登录 后方可回复, 如果你还没有账号请 注册新账号