Javascript 如果时钟有一位数字,则添加“0”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12278272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:35:26  来源:igfitidea点击:

Adding "0" if clock have one digit

javascriptclock

提问by Lukas

i have some clock script. Everything is fine and it's work perfectly but... i have one problem. If at the clock is set one digit hour or minute like 1:5 clock not adding "0" digit before. This what i'v done but it does't work. Can u help me, much thx?

我有一些时钟脚本。一切都很好,而且工作正常,但是...我有一个问题。如果在时钟上设置一位数的小时或分钟,如 1:5 时钟,之前不添加“0”数字。这是我所做的,但它不起作用。你能帮我吗,谢谢?

window.setInterval(function update_clock() {
    var currentTime = new Date();
    var currentHours = currentTime.getHours();
    var currentMinutes = currentTime.getMinutes();
    $.ajax({
        success: function (clock) {
            document.getElementById("hour").firstChild.nodeValue = currentHours;
            document.getElementById("minutes").firstChild.nodeValue = currentMinutes;
            if (currentMinutes.length == 1) {
                currentMinutes = "0" + currentMinutes;
            }
        }
    });
}, 999);

回答by dxh

You may use .sliceto extract a portion of a string. Pass a negative number to it, in order to slice from the end of the string.

您可以.slice用来提取字符串的一部分。向它传递一个负数,以便从字符串的末尾切片。

Therefore, the following is possible, and quite simple:

因此,以下是可能的,而且非常简单:

('0'+currentMinutes).slice(-2)

Concatenating with '0'makes sure that the target of the operation will always be a string. ('0'+currentMinutes)will yield a 2 or 3 letter string ("07" or "017", for instance). Slicing the last two characters off that string will give you a 0-padded two-digit number.

连接 with'0'确保操作的目标始终是字符串。('0'+currentMinutes)将产生一个 2 或 3 个字母的字符串(例如“07”或“017”)。切掉该字符串的最后两个字符将为您提供一个以 0 填充的两位数。

Note that the above would yield "00" if currentMinutesis 100, so it assumes that you know the values you'll be working with.

请注意,如果currentMinutesis 100,则上述内容将产生“00” ,因此它假定您知道将要使用的值。

This could be extracted to something more reusable:

这可以提取到更可重用的东西:

Number.prototype.zeroPad = function() {
   return ('0'+this).slice(-2);
};

That would allow you to write:

这将允许你写:

currentMinutes.zeroPad();

You could also make the length of the padding variable:

您还可以设置填充变量的长度:

Number.prototype.zeroPad = function(length) {
   length = length || 2; // defaults to 2 if no parameter is passed
   return (new Array(length).join('0')+this).slice(length*-1);
};

Which could be called as:

这可以称为:

currentMinutes.zeroPad(); // e.g. "07" or "17"
currentMinutes.zeroPad(3); // e.g. "007" or "017"

Note that while currentMinutes.zeroPad()will work, 7.zeroPad()would not.

请注意,虽然currentMinutes.zeroPad()会起作用,7.zeroPad()但不会。

回答by Marcelo De Zen

currentMinutesis a number, so it does not have the lengthproperty. Also, you must check the lengthbefore set the currentMinutesto the minuteselement.

currentMinutes是一个数字,所以它没有length属性。此外,您必须检查lengthbefore 将 设置currentMinutesminutes元素。

Something like:

就像是:

var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();

$.ajax({
    success: function (clock) {
        if (currentMinutes.toString().length == 1) {
            currentMinutes = "0" + currentMinutes;
        }

        document.getElementById("hour").firstChild.nodeValue = currentHours;
        document.getElementById("minutes").firstChild.nodeValue = currentMinutes;
    }
});

回答by alex

currentMinuteswon't have a lengthproperty, as it's a Number, not a String.

currentMinutes不会有length属性,因为它是Number,而不是String

You could force it to be a String.

你可以强制它是一个String.

if ((currentMinutes+'').length == 1) {
     currentMinutes = "0" + currentMinutes;
}

But, because you have a Number, you should make your condition...

但是,因为你有一个Number,你应该让你的条件......

if (currentMinutes < 10) {
     currentMinutes = "0" + currentMinutes;
}

If you were especially crazy, you could do...

如果你特别疯狂,你可以...

var hoursMinutes = ((new Date)+"").match(/\d+:\d+(?=:)/)[0].split(":");

回答by Pouya

Try using the padStart()method. Based on MDN docs, the padStart()method keeps padding the string with another string until it reaches the desired length. Linkto MDN docs on padStart().

尝试使用该padStart()方法。根据 MDN 文档,该padStart()方法不断用另一个字符串填充字符串,直到达到所需的长度。在 padStart() 上链接到 MDN 文档。

If you want to format your string to have 4 digits with leading zeros if less than 4 digits are available. The padStart()method can come to the rescue as follows:

如果您想将字符串格式化为 4 位带前导零的数字(如果可用数字少于 4 位)。该padStart()方法可以解决以下问题:

let str = "34"

str = str.padStart(4, "0") // results in "0034"
console.log(str)

An example of the date case:

日期案例的一个例子:

var now = new Date(); 
var year= now.getFullYear(); 
var month= (now.getMonth()+1).toString().padStart(2, "0");
var day= now.getDate().toString().padStart(2, "0");
var hour = now.getHours().toString().padStart(2, "0");
var minute = now.getMinutes().toString().padStart(2, "0");

document.getElementById("date").innerHTML =`${day}-${month}-${year}-${hour}:${minute}`;
 
<div id="date"></div>

回答by dureuill

You could also check sprintf()for javascript.

您还可以检查sprintf()是否有 javascript。

You could go with something as simple as:

您可以使用以下简单的方法:

sprintf("%02d:%02d", currentHours, currentMinutes);

Using functions that accept formatting lets you have much more control over your output, when you need to.

使用接受格式的函数可以让您在需要时更好地控制输出。

回答by sms247

in android(build in)

在android中(内置)

String time=String.format("%02d:%02d",hourOfDay,minute);

in javascript use (sprintf.js)

在 javascript 中使用 (sprintf.js)

int i = 1;
string s = sprintf("%02d", i);
document.write(s); // Prints "01"

sprintf.js: http://www.diveintojavascript.com/projects/javascript-sprintf

sprintf.js:http: //www.diveintojavascript.com/projects/javascript-sprintf

回答by Johan Hoeksma

Based on the other awnsers, I created this lines of code:

基于其他 awnsers,我创建了以下代码行:

var now = new Date(); 
var dd = now.getDate(); 
var mm = now.getMonth()+1;
var y = now.getFullYear(); 
var h = now.getHours();
var m = now.getMinutes();

function aZero(n) {
  return n.toString().length == 1 ?  n = '0' + n: n;
}

document.getElementById("out").innerHTML =
  aZero(dd) + "-" +
            aZero(mm) + "-" +
            y +  "   -  "   +
            aZero(h)  + ":" +
            aZero(m);
<div id="out">my time :D</div>

Cu next time.

下次铜。

回答by Developer_29

Try use ('0' + currentTime.getHours()).slice(-2)

尝试使用 ('0' + currentTime.getHours()).slice(-2)

Updated your Question -

更新了您的问题 -

window.setInterval(function update_clock() {
    var currentTime = new Date();
    var currentHours = ('0' + currentTime.getHours()).slice(-2);
    var currentMinutes = ('0' + currentTime.getMinutes()).slice(-2);
    $.ajax({
        success: function (clock) {
            document.getElementById("hour").firstChild.nodeValue = currentHours;
            document.getElementById("minutes").firstChild.nodeValue = currentMinutes;
            if (currentMinutes.length == 1) {
                currentMinutes = "0" + currentMinutes;
            }
        }
    });
}, 999);