js 怎么获取年月日时分秒中的时分秒

JavaScript05

js 怎么获取年月日时分秒中的时分秒,第1张

需要准备的材料分别有:电脑、html编辑器、浏览器。

1、首先,打开html编辑器,新建html文件,例如:index.html。

2、在index.html中的<script>标签,输入js代码:

var a = new Date()document.body.innerHTML

= '时:' + a.getHours() + '<br/>分:' + a.getMinutes() + '<br/>秒:' + a.getSeconds()

3、浏览器运行index.html页面,此时当前时间的时分秒都被js获取并打印了出来。

前言:需求里面有,做了就记录一下

第一种:获取当前月 当前周 的第一天 时分秒都为0,最后一天时分秒为23:59:59

ps:如果想获得指定日期的当前周,new Date('2020-1-2') 传参就可以了

//获取当前周

getTime(){

var date = new Date()

// 本周一的日期

date.setDate(date.getDate() - date.getDay() + 1)

var begin = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00"

// 本周日的日期

date.setDate(date.getDate() + 6)

var end = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 23:59:59"

let timeInfo={

begin:begin,

end:end

}

return timeInfo

}

//获取当前月

getMtime(){

var data=new Date()

data.setDate(1)

data.setHours(0)

data.setSeconds(0)

data.setMinutes(0)

var start = data.getTime()

var currentMonth = data.getMonth()

var nextMonth = ++currentMonth

var nextMonthFirstDay = new Date(

data.getFullYear(),

nextMonth,

1

)

var end = nextMonthFirstDay-1

let timeInfo={

begin: this.timestampToTime(start),//这里调用时间戳转年月日时分秒方法

end: this.timestampToTime(end)

}

return timeInfo

}

//时间戳转年月日时分秒方法

timestampToTime (cjsj) {

var date = new Date(cjsj) //时间戳为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())

return Y+M+D+h+m+s

}