gpt4 book ai didi

javascript - 将 "simple"时区偏移量 (-7) 转换为 "full"偏移量 (-07 :00)

转载 作者:行者123 更新时间:2023-12-03 04:50:50 25 4
gpt4 key购买 nike

好吧,两周来我一直在断断续续地试图解决这个问题,我已经很接近了,但我只需要最后的插入。我正在使用一个返回一堆事件的 API,这些事件都位于不同的时区。 API 只是为我提供了 -5-7 等的偏移量...我正在使用 moment.js 来解析时间和时区,然后它将返回用户的时区,它只接受“完整”时区字符串,例如 -07:00。所以我开始使用以下JS操作数据:

// number padding
function pad(n) {
if (n < 10 & n >=0){
return ("0" + n);
}
if(n < 0 & n > -11){
return ("-0" + Math.abs(n));
}
return n;
}

var timedate = '2017/03/02 1:05',
ampm = 'PM',
zone = '-5',
padded = pad(zone),
adjustedZone = parseInt(padded).toFixed(2),
adjustedTwo = adjustedZone.replace('.', ':');

这非常非常接近,除了 .toFixed 去掉了我的前导零并简单地返回 -5:00

在这种情况下如何保留前导零?我还需要支持 -10:00 时区,以及可能的任何正时区,尽管我的目标用户是北美,但支持所有时区将是一个巨大的优势。

非常感谢任何帮助,您还可以看到一个非常困惑的codepen here

最佳答案

注意:填充中的 -9 不是 -11,请参阅下面的代码 &您非常接近,只需“填充所需输出的时间分钟”(参见下面的输出):

// number padding
function pad(n) {
if (n < 10 & n >=0){
return ("0" + n);
}
// NOTE: -9 not -11
if(n < 0 & n >= -9){
return ("-0" + Math.abs(n));
}
return n;
}

var timedate = '2017/03/02 1:05',
ampm = 'PM',
zone = '-5',
//padded = pad(zone),
adjustedZone = parseInt(zone).toFixed(2),
adjustedTwo = adjustedZone.replace('.', ':');

//console.log(padded);
console.log('adjustedZone: ' + adjustedZone);
console.log('adjustedTwo: ' + adjustedTwo);

// pad the minutes of time for desired output
var a = adjustedTwo.split(':');
var output = pad(a[0]) + ':' + a[1];
console.log('final output: ' + output);

zone = '-10';
a = parseInt(zone).toFixed(2).split('.');
output = pad(a[0]) + ':' + a[1];
console.log('final output (for zone = ' + zone + '): ' + output);

关于javascript - 将 "simple"时区偏移量 (-7) 转换为 "full"偏移量 (-07 :00),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42663138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com