JavaScript 使用正确格式时计时器日期无效

JavaScript Timer date not Valid when using correct format

我有一个字符串,由用户在表单中输入的 cookie 组合在一起。这是代码:

var monthCookie     = getCookieValue("monthUserPref")
var dayCookie       = getCookieValue("dayUserPref")
var hourCookie      = getCookieValue("hourUserPref")
var minuteCookie    = getCookieValue("minuteUserPref")
var ampmCookie      = getCookieValue("ampmUserPref")
var currentYear     = new Date().getFullYear();
var monthCookie     = getMonth(monthCookie);

var currentEndDateForClockNoTZChange = "'"+currentYear+", "+monthCookie+", "+dayCookie+", "+hourCookie+", "+minuteCookie+", 0'"

var endTimeNoOffset = new Date(currentEndDateForClockNoTZChange)
var endTimeOffset   = endTimeNoOffset.getTimezoneOffset();

alert("Put together time is "+currentEndDateForClockNoTZChange)
alert(endTimeNoOffset)
alert("month cookie reads '"+monthCookie+"', day cookie reads '"+dayCookie+"', hour cookie reads '"+hourCookie+"', minute cookie reads '"+minuteCookie+"', ampm cookie reads '"+ampmCookie+"'.");
alert("timer offset is "+endTimeOffset)

第一个警报显示为 "Put together time is '2022, 1, 11, 1, 11, 0' "
第二个警报说 Invalid Date",
第三个警报说,month cookie reads '1'
day cookie reads '11',
hour cookie reads '1',
minute cookie reads '11',
ampm cookie reads 'PM'.",
第四个警报说 "Timer offset is NaN".

我必须使用不同的格式吗?

这样:

您希望使用 Date() 构造函数的方式是关于整数参数,而不是字符串

let
  monthCookie     = Number(getCookieValue('monthUserPref'))
, dayCookie       = Number(getCookieValue('dayUserPref'))
, hourCookie      = Number(getCookieValue('hourUserPref'))
, minuteCookie    = Number(getCookieValue('minuteUserPref'))
, ampmCookie      = Number(getCookieValue('ampmUserPref'))
, currentYear     = new Date().getFullYear()
, monthCookie     = getMonth(monthCookie)
, endTimeNoOffset = new Date( currentYear, monthCookie, dayCookie, hourCookie, minuteCookie, 0 )
, endTimeOffset   = endTimeNoOffset.getTimezoneOffset()
  ;