Convert timezone offset number of hours to timezon

2019-08-25 08:40发布

问题:

I am using WordPress and jQuery Timepicker.

Wordpress gives timezone offset in hours: like +2 or -3.5

jQuery Timepicker takes offset in military hours: +0200 or -0330

I am currently using something like this:

gmt_offset = -4;
hrs_offset = gmt_offset.replace('-', '-0') + "00";

= -0400

But that will break if the offset is not a single negative digit.

gmt_offset = -3.5;
hrs_offset = gmt_offset.replace('-', '-0') + "00";

= -03.500  //No good...

need: -0330

Ack! Can someone help me figure this out?

回答1:

Split the offset into 2 parts using .split(".").

Give the hour part a "0" if it is less than 10. Then append a negative sign if it is originally negative.

var negative = hour < 0 ? true : false;
hour = Math.abs(hour) < 10 ? "0" + Math.abs(hour) : Math.abs(hour);
hour = negative ? "-" + hour : "+" + hour;

To calculate the minutes part, multiply it by 6.

(time[1]*6).toString()

Here's the final function:

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));

See DEMO.



回答2:

function convert(gmt_offset) {
     var sign ="+";
     if(gmt_offset < 0) {
         sign="-";
         gmt_offset *= -1;
     }
     var hours = "0"+Math.floor(gmt_offset).toString();
     var minutes = "0"+(Math.round(gmt_offset % 1 * 60)).toString();
     return sign + hours.substr(hours.length - 2) + minutes.substr(minutes.length - 2);
}


回答3:

Here's a nicely compact version:

function militaryGMTOffsetFromNumeric(offset) {
   var dt = new Date(
      Math.abs(offset) * 3600000 + new Date(2000, 0).getTime()
   ).toTimeString();
   return (offset < 0 ? '-' : '+') + dt.substr(0,2) + dt.substr(3,2);
}

For example, militaryGMTOffsetFromNumeric(-3.5) returns -0330.