在几分钟内领先零 [英] Leading zeros in minutes
问题描述
我创建了一个时钟放在我网站的标题中。时间不显示零分钟< 10.例如,如果时间是10:50,它将只显示10:5,我找到了解决方案但不确定如何实现它。如果有更好的方法,请分享。
I created a clock to be placed in the header of my website. The time is not displaying a zero for minutes < 10. For example if the time is 10:50, it will only show 10:5 ,I found a solution but unsure of how to implement it. Also if there is a better method please share.
var current;
window.onload = function () {
current = new Date();
document.getElementById("clock").innerHTML = current.getHours() + ":" + current.getMinutes();
这就是我所需要的
if (minutes < 10)
minutes = "0" + minutes
这是我时钟的容器
<span id="clock"> </span>
推荐答案
因为你可能会遇到表达问题未来沿着同样的路线,我建议为Javascript挑选一个最喜欢的字符串格式函数。
Since you're likely to run into presentational issues in the future along the same lines, I'd recommend picking a favorite string formatting function for Javascript.
一些例子:
- http://www.masterdata .se / r / string_format_for_javascript /
- http ://www.diveintojavascript.com/projects/javascript-sprintf
- http://www.masterdata.se/r/string_format_for_javascript/
- http://www.diveintojavascript.com/projects/javascript-sprintf
然后您可以执行类似<$ c的操作$ c>{0:00}:{1:00}。format(current.getHours(),current.getMinutes())甚至更好,
Then you can do something like "{0:00}:{1:00}".format(current.getHours(), current.getMinutes())
or even better,
var d = new Date();
var s = d.format("hh:mm:ss tt");
// Result: "02:28:06 PM"
这篇关于在几分钟内领先零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!