当使用date.getMonth()时,为什么我的结果会偏离3



在此处输入图像描述我得到了console.log(monthnum(的不同结果;和console.log(date.getMonth(((。我不明白他们为什么会不同,我希望他们是一样的。我已经包含了我的控制台显示的图像。正如你所看到的,当我期待8的时候,monthnum返回11。

虽然我认为相关的部分已经到了最后,但我已经包含了我的整个剧本以备不时之需。

const HOURHAND = document.querySelector("#hourhand");
const MINUTEHAND = document.querySelector("#minutehand");
const SECONDHAND = document.querySelector("#secondhand");


var date = new Date();
var whathour = date.getHours();
var whatminute = date.getMinutes();
var whatsecond = date.getSeconds();

var secdeg = whatsecond*6;
var mindeg = whatminute*6+whatsecond/10;
var hourdeg = whathour*30+whatminute/2+whatsecond/120;


let positionhour = hourdeg;
let positionminute =mindeg;
let positionsecond =secdeg;


HOURHAND.style.cssText = "transform: rotate("+positionhour + "deg)";
MINUTEHAND.style.cssText = "transform: rotate("+positionminute+"deg)";
SECONDHAND.style.cssText = "transform: rotate("+positionsecond +"deg)";
let adjhour;
if (whathour>12 && whatminute > 9) {adjhour = whathour-12; document.querySelector("#digtimehere").innerHTML = "The time is currently " + adjhour +":" + whatminute + " PM." ;}
else if (whathour>12 && whatminute <10) {adjhour = whathour-12; document.querySelector("#digtimehere").innerHTML = "The time is currently " + adjhour +":" + "0" + whatminute + " PM." ;}
else if (whatminute > 9) {adjhour = whathour; document.querySelector("#digtimehere").innerHTML = "The time is currently " + adjhour +":" + whatminute + " AM." ;}
else {adjhour = whathour; document.querySelector("#digtimehere").innerHTML = "The time is currently " + adjhour +":" + "0" + whatminute + " AM." ;}

var daynum = date.getDay();
if (daynum = 0) {whatday = "Sunday";}
if (daynum = 1) {whatday = "Monday";}
if (daynum = 2) {whatday = "Tuesday";}
if (daynum = 3) {whatday = "Wednesday";}
if (daynum = 4) {whatday = "Thursday";}
if (daynum = 5) {whatday = "Friday";}
if (daynum = 6)  {whatday = "Saturday";}
var monthnum = date.getMonth();
if (monthnum = 0) {whatmonth = "January";}
if (monthnum = 1) {whatmonth = "February";}
if (monthnum = 2) {whatmonth = "March";}
if (monthnum = 3) {whatmonth = "April";}
if (monthnum = 4) {whatmonth = "May";}
if (monthnum = 5) {whatmonth = "June";}
if (monthnum = 6) {whatmonth = "July";}
if (monthnum = 7) {whatmonth = "August";}
if (monthnum = 8) {whatmonth = "September";}
if (monthnum = 9) {whatmonth = "October";} 
if (monthnum = 10) {whatmonth = "November";}
if (monthnum = 11) {whatmonth = "December";}
var thedate = date.getDate();
document.querySelector("#datehere").innerHTML = "Today is " + whatday + ", " + whatmonth + " " + thedate + ".";
console.log(monthnum);
console.log(date);
console.log(date.getMonth())

当使用单个=时,您正在分配值

如果要进行比较,请使用==

if( monthnum == 8){...}

所以它的逻辑月数=11,因为这是最后一次赋值;(

顺便说一句,如果你想用月份的名称来显示,你可以使用以下代码:

var options = { month: 'long'};
whatmonth = new Intl.DateTimeFormat('en-US', options).format(date);

最新更新