Javascript日期:如果需要,确保getMinutes(),getHours(),getSeconds()将0放在前面 [英] Javascript Date: Ensure getMinutes(), getHours(), getSeconds() puts 0 in front if necessary

查看:254
本文介绍了Javascript日期:如果需要,确保getMinutes(),getHours(),getSeconds()将0放在前面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找一种创造性的方式来确保来自javascript Date对象的getHours,getMinutes和getSeconds()方法的值返回06而不是 6 (例如)。有没有什么参数我不知道?显然,我可以编写一个功能,通过检查长度,并在需要的时候加上一个0,但我认为可能会有更多的流线型。 p>

谢谢。

解决方案

据我所知,没有。而且我一直都这么做,把日期转换成XML dateTime格式。



同样重要的是,你列出的那些方法返回一个数字,而不是一个字符串。 / p>

当然,您可以通过修改 Date.prototype 来添加这些。

  Date.prototype.getHoursTwoDigits = function()
{
var retval = this.getHours();
if(retval< 10)
{
return(0+ retval.toString());
}
else
{
return retval.toString();
}
}

var date = new Date();
date.getHoursTwoDigits();


Looking for a creative way to be sure values that come from the getHours, getMinutes, and getSeconds() method for the javascript Date object return "06" instead of 6 (for example). Are there any parameters that I don't know about? Obviously I could write a function that does it by checking the length and prepending a "0" if need be, but I thought there might be something more streamlined than that.

Thanks.

解决方案

As far as I know, there's not. And I do this all the time for converting dates to the XML dateTime format.

It's also important to note that those methods you list return a number, not a string.

You can, of course, add these yourself by modifying Date.prototype.

Date.prototype.getHoursTwoDigits = function()
{
    var retval = this.getHours();
    if (retval < 10)
    {
        return ("0" + retval.toString());
    }
    else
    {
        return retval.toString();
    }
}

var date = new Date();
date.getHoursTwoDigits();

这篇关于Javascript日期:如果需要,确保getMinutes(),getHours(),getSeconds()将0放在前面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆