<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>获取当前时间</title>
</head>
<body>
<script type="text/javascript">
/**
*补0
*/
function getzf(num) {
if (parseInt(num) < 10) {
num = '0' + num;
}
return num;
}
/**
*获取当前时间
*format=1精确到天
*format=2精确到分
*/
function getCurrentDate(format) {
var now = new Date();
var year = now.getFullYear(); //得到年份
var month = now.getMonth() + 1;//得到月份 JS返回的是索引值而且是从0开始的,所以要加1了,要是不加1就是0月了!
var day = now.getDate();//得到日期
var hours = now.getHours();//得到小时
var minu = now.getMinutes();//得到分钟
var sec = now.getSeconds();//得到秒
var timeValue ="" + ((hours >= 12) ? "PM" : "AM" )
//12hrs
var hour = "";
if(hours>=12){
hour = hours-12;
}else{
hour = hours;
}
//if (month < 10) month = "0" + month;
//if (day < 10) date = "0" + date;
//if (hour < 10) hour = "0" + hour;
//if (minu < 10) minu = "0" + minu;
//if (sec < 10) sec = "0" + sec;
var time = "";
//精确到天
if(format==1){
time = year + "-" + getzf(month) + "-" + day;
}
//精确到秒
else if(format==2){
time = year + "-" + month + "-" + getzf(day)+ " " + hour + ":" + getzf(minu) + ":" + getzf(sec) + " " + timeValue ;
}
return time;
}
alert(getCurrentDate(2));
</script>
</body>
</html>