gpt4 book ai didi

Javascript Date : Ensure getMinutes(), getHours(), getSeconds() 如果需要的话在前面加0

转载 作者:行者123 更新时间:2023-12-03 00:32:21 27 4
gpt4 key购买 nike

寻找一种创造性的方法来确保来自 javascript Date 对象的 getHours、getMinutes 和 getSeconds() 方法的值返回 "06" 而不是 6(例如)。有什么我不知道的参数吗?显然,我可以编写一个函数,通过检查长度并在需要时添加 "0" 来完成此操作,但我认为可能有比这更简化的方法。

谢谢。

最佳答案

与@jdmichal的解决方案类似,发布是因为我更喜欢短一点的内容:

function pad(n) { return ("0" + n).slice(-2); }

pad(6); // -> "06"
pad(12); // -> "12"

您可以将此方法添加到 Number.prototype 中,而不是向 Date.prototype 添加单独的方法:

Number.prototype.pad = function (len) {
return (new Array(len+1).join("0") + this).slice(-len);
}

// Now .pad() is callable on any number, including those returned by
var time = date.getHours().pad(2) + ":"
+ date.getMinutes().pad(2) + ":"
+ date.getSeconds().pad(2);

关于Javascript Date : Ensure getMinutes(), getHours(), getSeconds() 如果需要的话在前面加0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3313875/

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