我有这个代码,用于更改时间和日期 - 根据时区差异,例如5
小时(由/////TIME ZONE DIFFERECEN/////
表示),但它不起作用我将如何期望它跑;例如:在适用的情况下不更改日期和时间。任何人都可以提供帮助。
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var months = ["31"];
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
months.push("29");
} else {
months.push("28");
}
monthsappend = ["31", "30", "31", "30", "31", "31", "30", "31", "20", "31"];
months.concat(monthsappend);
time = "7:00pm";
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s?([AaPp][Mm]?)$/)[1];
var pm = ['P', 'p', 'PM', 'pM', 'pm', 'Pm'];
var am = ['A', 'a', 'AM', 'aM', 'am', 'Am'];
if (pm.indexOf(AMPM) >= 0 && hours < 12) hours = hours + 12;
if (am.indexOf(AMPM) >= 0 && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
timearr = [sHours, sMinutes];
timearr[0] += 5;
/////////////////////////////// TIME ZONE DIFFERENCE////////////////////////////
if (time.toLowerCase().includes("pm")) {
}
if (timearr < 0) {
day -= 1;
if (day == 0) {
month -= 1;
if (month == 0) {
month = 12;
year = dateObj.getFullYear() - 1;
}
day = months[month - 1];
}
} else {
if (timearr => 24) {
timearr[0] = 24 - timearr[0];
if (day == months[month - 1]) {
day = 1;
month += 1;
if (month == 12) {
month = 1;
year += 1;
}
}
}
}
newdate = day + "/" + month + "/" + year;
console.log(newdate);
console.log(timearr[0]);
&#13;
答案 0 :(得分:2)
好吧,首先我要指出错误:
=>
而不是大于或等于运算符>=
(感谢RobG)。timearr
视为一个数组,稍后将其视为一个数字。我认为您打算比较timearr[0]
。"19" + 5 === "195"
。你需要在这里处理数字,而不是字符串。timearr[0]
声明的第一部分调整if
。timearr[0]
的第二部分中调整if
时,您会以相反的顺序进行减法。 (24 - 26 === -2
,您可能需要26 - 24 === 2
)。month += 1
之前,您会增加if (month == 12)
。要么需要在其他地方,要么您必须检查month === 13
。==
更适合的地方使用===
。var
时忘了timearr
。总的来说,您似乎正在尝试以UTC + 5输出日/月/年格式的当前日期。有许多更简单的方法可以做你所要求的。例如:
// Get the current moment in time, as a Date object.
var d = new Date();
// Add 5 hours of absolute duration. The setter handles the bubbling for you.
// Be sure to use UTC here, to avoid interference from transitions of the local time zone.
d.setUTCHours(d.getUTCHours() + 5);
// Get the properties we want to display.
var year = d.getUTCFullYear();
var month = d.getUTCMonth() + 1;
var day = d.getUTCDate();
// Construct the string for output in the desired format.
var s = day + '/' + month + '/' + year;
var s = moment().utcOffset(5).format('D/M/YYYY');
请记住“时区!=偏移”。事实上,世界上目前使用UTC+5
的所有地方全年使用它(例如巴基斯坦),但如果你在谈论美国东部时间,那么某些地方会UTC-5
今年的其他部分,UTC-4
。