javascript toLocaleTimeString仅2位数秒或分钟不起作用

时间:2019-06-06 01:47:01

标签: javascript html date locale

例如:

const options = {
    			       timeZone:"America/Sao_Paulo",
    			       hour12 : false,
    			       hour:  "2-digit",
    			       //minute: "2-digit",
    			       //second: "2-digit"
    			    };
              
console.log(new Date("2019-06-05T00:01:00").toLocaleTimeString("pt-BR",options));

它显示00,就可以了。但是,如果我仅以分钟或秒为单位进行尝试,则仅显示一位数字。

const options = {
    			       timeZone:"America/Sao_Paulo",
    			       hour12 : false,
    			       //hour:  "2-digit",
    			       minute: "2-digit",
    			       //second: "2-digit"
    			    };
console.log(new Date("2019-06-05T00:01:00").toLocaleTimeString("pt-BR",options));

const options2 = {
    			       timeZone:"America/Sao_Paulo",
    			       hour12 : false,
    			       //hour:  "2-digit",
    			       //minute: "2-digit",
    			       second: "2-digit"
    			    };
console.log(new Date("2019-06-05T00:01:00").toLocaleTimeString("pt-BR",options2));

获得两位数的分钟或秒需要什么?

2 个答案:

答案 0 :(得分:0)

不幸的是,chrome和Firefox无法很好地做到这一点。最好的方法是格式化小时,分钟和秒,这将使其始终打印两位数。

const options = {
    timeZone:"America/Sao_Paulo",    
    hour12 : false,
    hour:  "2-digit",
    minute: "2-digit",
    second: "2-digit"
};

并将其解析为帖子。

答案 1 :(得分:0)

谢谢大家。可悲的是,我不得不将时间分为几小时,几分钟和几秒钟,并使用数组索引来获取我想要的东西:

let d = new Date('2019-06-06T00:01:02');
    		  
const options = {
     timeZone:"America/Sao_Paulo",
     hour12 : false,
     hour:  "2-digit",
     minute: "2-digit",
     second: "2-digit"
  };
    		  
let horario = d.toLocaleTimeString("pt-BR",options);
    		  
let array_horario = horario.split(':');
    		  
console.log(array_horario[0]);
console.log(array_horario[1]);
console.log(array_horario[2]);