本文为了实现javascript获取当前时间,在html加一个按钮,为了增加触发事件
<input type="button" id="time" value="time" name="aa" οnclick="getNowFormatDate()">
接下来是编写js里面的getNowFormatDate() 方法,用来实现js获取当前时间
function getNowFormatDate() {
var date = new Date();
var seperator1 = "-";
var year = date.getFullYear();
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = year + seperator1 + month + seperator1 + strDate;
return currentdate;
}
接下来就是组合在一块,下面是完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>time</title>
</head>
<body>
<input type="button" id="time" value="time" name="aa" οnclick="getNowFormatDate()">
</body>
<script>
//获取当前时间,格式YYYY-MM-DD
function getNowFormatDate() {
var date = new Date();
var seperator1 = "-";
var year = date.getFullYear();
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = year + seperator1 + month + seperator1 + strDate;
alert(currentdate);
return currentdate;
}
</script>
</html>