我正在使用 WordPress 和 jQuery Timepicker。
Wordpress 给出时区偏移量(以小时为单位):例如 +2 或 -3.5
jQuery Timepicker 在军事时间中进行偏移:+0200 或 -0330
我目前正在使用这样的东西:
gmt_offset = -4;
hrs_offset = gmt_offset.replace('-', '-0') + "00";
= -0400
但是如果偏移量不是单个负数,就会中断。
gmt_offset = -3.5;
hrs_offset = gmt_offset.replace('-', '-0') + "00";
= -03.500 //No good...
need: -0330
确认!有人可以帮我解决这个问题吗?
最佳答案
使用 .split(".") 将偏移量分成两部分
。
如果小时部分小于 10,则给它“0”。如果原来是负数,则附加一个负号。
var negative = hour < 0 ? true : false;
hour = Math.abs(hour) < 10 ? "0" + Math.abs(hour) : Math.abs(hour);
hour = negative ? "-" + hour : "+" + hour;
要计算分钟部分,请将其乘以 6。
(time[1]*6).toString()
这是最终的函数:
function convertOffset(gmt_offset) {
var time = gmt_offset.toString().split(".");
var hour = parseInt(time[0]);
var negative = hour < 0 ? true : false;
hour = Math.abs(hour) < 10 ? "0" + Math.abs(hour) : Math.abs(hour);
hour = negative ? "-" + hour : "+" + hour;
return time[1] ? hour+(time[1]*6).toString() : hour + "00";
}
document.write(convertOffset(-3.5));
参见DEMO .
关于javascript - 将时区偏移小时数转换为时区偏移(军事?)小时数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15687872/