使用js获取当前时间且按照格式输出
1.首先先创建一个对象存放所有获取的时间
var date = new Date();
var obj = {
YYYY:date.getFullYear(), //获取了年 对应key:YYYY
MM:date.getMonth()+1, //获取了月 对应key:MM
DD:date.getDate(), //获取了日 对应key:DD
hh:date.getHours(), //获取了时 对应key:hh
mm:date.getMinutes(), //获取了分 对应key:mm
ss:date.getSeconds(), //获取了秒 对应key:ss
}
2.创建改变后的样式
var format = “YYYY-MM-DD hh:mm:ss”
3.遍历对象
for(x in obj){
if(obj[x]<10){
// 当数组的值小于10 在数组前面加一个’0‘
obj[x] = ‘0’ +obj[x]
}
//
format = format.replace([x],obj[x])
// 通过replace可以将repalce[x]改变成obj[x]里的内容
}
document.write(format)
4.结果
<script>
var date =new Date();
var obj = {
YYYY:date.getFullYear(),
MM:date.getMonth()+1,
DD:date.getDate(),
hh:date.getHours(),
mm:date.getMinutes(),
ss:date.getSeconds(),
}
var format = 'YYYY-MM-DD hh:mm:ss'
// 定义改变后的格式
for(var x in obj){
// 遍历对象 x为key
if(obj[x]<10){
// 当获取的值小于10 加一个0在前面
obj[x] = '0' +obj[x]
}
format = format.replace([x],obj[x])
// x 为键 replace[x]值,replace[x]替换成obj[x]
}
document.write(format)
</script>