有的时候我们可能需要获取当前时间,比如:当发表文章时,需要加上当前的时间点;
当我们发表评论的时侯,也需要当前时间.....
首先说一下JS中的Date对象
1、Date().getFullYear()
用于获取年份
2、Date().getMonth()
获取当前月份,注意返回值是0-11,需要在后面+1
3、Date().getDate()
获取当前日
4、Date().getHours()
获取当前时刻
5、new Date().getMinutes()
获取分钟
6、new Date().getSeconds()
获取秒数
下面示例:
在js文件中写入以下代码:
let dataTime
let yy = new Date().getFullYear()
let mm = new Date().getMonth()+1
let dd = new Date().getDate()
let hh = new Date().getHours()
let mf = new Date().getMinutes()<10?'0'+new Date().getMinutes():
new Date().getMinutes()
let ss = new Date().getSeconds()<10?'0'+new Date().getSeconds():
new Date().getSeconds()
dataTime = `${yy}-${mm}-${dd} ${hh}:${mf}:${ss}`;
那么dataTime返回以下格式的时间:
以下代码:
let dataTime
let yy = new Date().getFullYear()
let mm = new Date().getMonth()+1
let dd = new Date().getDate()
dataTime = `${yy}-${mm}-${dd}`;
返回以下格式的时间:
以上就是获取当前时间的实现,可能不是很详细,只供实现参考。