Javascript 日期 - 在适用的情况下,前导 0 表示天数和月数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6979697/
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-24 00:05:52  来源:igfitidea点击:

Javascript date - Leading 0 for days and months where applicable

javascriptdate

提问by Harry

Is there a clean way of adding a 0 in front of the day or month when the day or month is less than 10:

当日或月小于 10 时,是否有一种干净的方法在日或月前添加 0:

var myDate = new Date();
var prettyDate =(myDate.getFullYear() +'-'+ myDate.getMonth()) +'-'+ myDate.getDate();

This would output as:

这将输出为:

2011-8-8

I would like it to be:

我希望它是:

2011-08-08

回答by Paul

No, there is no nice way to do it. You have to resort to something like:

不,没有好的方法可以做到这一点。你必须求助于类似的事情:

var myDate = new Date();

var year = myDate.getFullYear();

var month = myDate.getMonth() + 1;
if(month <= 9)
    month = '0'+month;

var day= myDate.getDate();
if(day <= 9)
    day = '0'+day;

var prettyDate = year +'-'+ month +'-'+ day;

回答by mivk

The format you seem to want looks like ISO. So take advantage of toISOString():

您似乎想要的格式看起来像 ISO。所以利用toISOString()

var d = new Date();
var date = d.toISOString().slice(0,10); // "2014-05-12"

回答by Makram Saleh

var myDate = new Date();
var m = myDate.getMonth() + 1;
var d = myDate.getDate();
m = m > 9 ? m : "0"+m;
d = d > 9 ? d : "0"+d;
var prettyDate =(myDate.getFullYear() +'-'+ m) +'-'+ d;

...and a sample: http://jsfiddle.net/gFkaP/

...和一个示例:http: //jsfiddle.net/gFkaP/

回答by Dunhamzzz

You will have to manually check if it needs a leading zero and add it if necessary...

您必须手动检查它是否需要前导零并在必要时添加它...

var m = myDate.getMonth();
var d =  myDate.getDate();

if (m < 10) {
    m = '0' + m
}

if (d < 10) {
    d = '0' + d
}

var prettyDate = myDate.getFullYear() +'-'+ m +'-'+ d;

回答by Alnitak

Yes, get String.jsby Rumata and then use:

是的,String.js通过 Rumata获取,然后使用:

'%04d-%02d-%02d'.sprintf(myDate.getFullYear(),
                         myDate.getMonth() + 1,
                         myDate.getDate());

NB: don't forget the + 1on the month field. The Dateobject's month field starts from zero, not one!

注意:不要忘记+ 1月字段上的。该Date对象的月份字段从零,而不是一个开始!

If you don't want to use an extra library, a trivial inline function will do the job of adding the leading zeroes:

如果您不想使用额外的库,一个简单的内联函数将完成添加前导零的工作:

function date2str(d) {
    function fix2(n) {
        return (n < 10) ? '0' + n : n;
    }
    return d.getFullYear() + '-' +
           fix2(d.getMonth() + 1) + '-' +
           fix2(d.getDate());
 }

or even add it to the Dateprototype:

甚至将其添加到Date原型中:

Date.prototype.ISO8601date = function() {
    function fix2(n) {
        return (n < 10) ? '0' + n : n;
    }
    return this.getFullYear() + '-' +
           fix2(this.getMonth() + 1) + '-' +
           fix2(this.getDate());
 }

usage (see http://jsfiddle.net/alnitak/M5S5u/):

用法(见http://jsfiddle.net/alnitak/M5S5u/):

 var d = new Date();
 var s = d.ISO8601date();

回答by Arsalan

For Month, var month = ("0" + (myDate.getMonth() + 1)).slice(-2);

月份, var month = ("0" + (myDate.getMonth() + 1)).slice(-2);

For Day, var day = ("0" + (myDate.getDate() + 1)).slice(-2);

对于日, var day = ("0" + (myDate.getDate() + 1)).slice(-2);

回答by Bablu Ahmed

You can try like this

你可以这样试试

For day:

当天:

("0" + new Date().getDate()).slice(-2)

For month:

月份:

("0" + (new Date().getMonth() + 1)).slice(-2)

For year:

年份:

new Date().getFullYear();

回答by Shven

The easiest way to do this is to prepend a zeroand then use .slice(-2). With this function you always return the last 2 characters of a string.

最简单的方法是在前面加上 azero然后使用.slice(-2). 使用此函数,您始终返回 a 的最后 2 个字符string

var month = 8;

var month = 8;

var monthWithLeadingZeros = ('0' + month).slice(-2);

var monthWithLeadingZeros = ('0' + month).slice(-2);

Checkout this example: http://codepen.io/Shven/pen/vLgQMQ?editors=101

查看这个例子:http: //codepen.io/Shven/pen/vLgQMQ?editors=101

回答by fredrik

Unfortunately there's no built-in date-format in javascript. Either use a existing library (example http://blog.stevenlevithan.com/archives/date-time-format) or build your own method for adding a leading zero.

不幸的是,javascript 中没有内置日期格式。使用现有的库(例如http://blog.stevenlevithan.com/archives/date-time-format)或构建您自己的方法来添加前导零。

var addLeadingZeroIfNeeded = function addLeadingZeroIfNeeded(dateNumber) {
        if (String(dateNumber).length === 1) {
            return '0' + String(dateNumber);
        }

        return String(dateNumber);
    },
    myDate = new Date(),
    prettyDate;

prettyDate = myDate.getFullYear() + '-' + addLeadingZeroIfNeeded(myDate.getMonth()) + '-' + addLeadingZeroIfNeeded(myDate.getDate());

EDIT

编辑

As Alnitak said, keep in mind that month i JavaScript starts on 0 not 1.

正如 Alnitak 所说,请记住,JavaScript 从 0 开始,而不是从 1 开始。