所以我想让我的日期显示在我的innerhtml中,但问题是我无法找出为什么它没有间隔开或像这样显示
我的代码JS代码是
function myFunction() {
// day of the month, day of the week month and year
var p = document.getElementById("mydata");
var mydate = new Date();
var day = mydate.getDay();
var month = mydate.getMonth();
var year = mydate.getYear();
var d = mydate.getDate();
var dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
p.innerHTML = "Today is the " + d + dayNames[day] + month + year;
}
而html是
<!DOCTYPE html>
<html lang="en">
<head>
<!-- link to external JS file. Note that <script> has an
end </script> tag -->
<meta charset="utf-8">
<title> Task 5 </title>
<link href="style.css" type="text/css" rel="stylesheet">
<script src="task5.js" type="text/javascript"></script>
</head>
<body>
<!-- Create a paragraph with id mydata -->
<div id="box">
<p id="mydata"> Todays Date</p>
<p> <button onclick="myFunction();"> Click </button></p>
</div>
</body>
</html>
答案 0 :(得分:3)
您应该在月份和年份中添加数字,如下所示:
function myFunction() {
var p = document.getElementById("mydata");
var mydate = new Date();
var day = mydate.getDay();
var month = mydate.getMonth() + 1;
var year = mydate.getYear() + 1900;
var d = mydate.getDate();
var dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
p.innerHTML = "Today is " + d + "(" + dayNames[day] + ")" + month + " " + year;
}
答案 1 :(得分:1)
您的代码有两个问题。
年份是相对于1900年的,因此您需要添加年份。
var year = mydate.getYear()+ 1900;
您需要显式添加空格和括号。
p.innerHTML =“今天是” + d +“(” + dayNames [day] +“)” +月+“” +年;
答案 2 :(得分:1)
使用getFullYear作为年份,获取正确的月份名称并正确构建日期字符串。
2018-10-22T09:19:31.761-03:00[America/Sao_Paulo]
2018-10-22T09:19:31.761-03:00[America/Sao_Paulo]
2018-10-22T08:19:31.761-04:00[America/Cuiaba]
2018-10-22T08:19:31.761-04:00[GMT-04:00]
function myFunction() {
// day of the month, day of the week month and year
var p = document.getElementById("mydata");
var mydate = new Date();
var day = mydate.getDay();
var month = mydate.getMonth();
var year = mydate.getFullYear();
var d = mydate.getDate();
var dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
p.innerHTML = "Today is the " + d + " (" + dayNames[day] + ") " + monthShortNames[month] + " " + year;
}
答案 3 :(得分:1)
解决了,谢谢大家。
function myFunction() {
// day of the month, day of the week month and year
var p = document.getElementById("mydata");
var mydate = new Date();
var day = mydate.getDay();
var month = mydate.getMonth();
var year = mydate.getYear() + 1900;
var d = mydate.getDate();
var dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var months = ["Jan", "Feb", "Mar", "April", "May", "June", "July", "August", "September", "Oct"];
p.innerHTML = "Today is the " + d + " " + "("+ dayNames[day]+")" + " " + months[month] + " " + year;
" (" + months[month] + ")"
}