Javascript 添加前导零到日期

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

Javascript add leading zeroes to date

javascriptdatedate-formattime-formatleading-zero

提问by Julian Coates

I've created this script to calculate the date for 10 days in advance in the format of dd/mm/yyyy:

我创建了这个脚本,以 dd/mm/yyyy 格式提前计算 10 天的日期:

var MyDate = new Date();
var MyDateString = new Date();
MyDate.setDate(MyDate.getDate()+10);
MyDateString = MyDate.getDate() + '/' + (MyDate.getMonth()+1) + '/' + MyDate.getFullYear();

I need to have the date appear with leading zeroes on the day and month component by way of adding these rules to the script. I can't seem to get it to work.

通过将这些规则添加到脚本中,我需要在日期和月份组件上显示带有前导零的日期。我似乎无法让它工作。

if (MyDate.getMonth < 10)getMonth = '0' + getMonth;

and

if (MyDate.getDate <10)get.Date = '0' + getDate;

If someone could show me where to insert these into the script I would be really appreciative.

如果有人可以告诉我在哪里将这些插入到脚本中,我将不胜感激。

回答by user113716

Try this: http://jsfiddle.net/xA5B7/

试试这个:http: //jsfiddle.net/xA5B7/

var MyDate = new Date();
var MyDateString;

MyDate.setDate(MyDate.getDate() + 20);

MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/'
             + ('0' + (MyDate.getMonth()+1)).slice(-2) + '/'
             + MyDate.getFullYear();


EDIT:

编辑:

To explain, .slice(-2)gives us the lasttwo characters of the string.

为了解释,.slice(-2)给了我们字符串的最后两个字符。

So no matter what, we can add "0"to the day or month, and just ask for the last two since those are always the two we want.

所以无论如何,我们可以添加"0"到日期或月份,并只要求最后两个,因为那些总是我们想要的两个。

So if the MyDate.getMonth()returns 9, it will be:

所以如果MyDate.getMonth()返回9,它将是:

("0" + "9") // Giving us "09"

so adding .slice(-2)on that gives us the last two characters which is:

所以加上.slice(-2)它给了我们最后两个字符,即:

("0" + "9").slice(-2)
"09"

But if MyDate.getMonth()returns 10, it will be:

但如果MyDate.getMonth()返回10,它将是:

("0" + "10") // Giving us "010"

so adding .slice(-2)gives us the last two characters, or:

所以添加.slice(-2)给我们最后两个字符,或者:

("0" + "10").slice(-2)
"10"

回答by Alex Ross

Here is an example from the Date object docson the Mozilla Developer Network using a custom "pad" function, without having to extend Javascript's Number prototype. The handy function they give as an example is

这是Mozilla 开发者网络上Date 对象文档中的一个示例,它使用自定义的“pad”函数,而无需扩展 Javascript 的 Number 原型。他们举个例子的方便的功能是

function pad(n){return n<10 ? '0'+n : n}

And below is it being used in context.

下面是它在上下文中的使用。

/* use a function for the exact format desired... */
function ISODateString(d){
    function pad(n){return n<10 ? '0'+n : n}
    return d.getUTCFullYear()+'-'
    + pad(d.getUTCMonth()+1)+'-'
    + pad(d.getUTCDate())+'T'
    + pad(d.getUTCHours())+':'
    + pad(d.getUTCMinutes())+':'
    + pad(d.getUTCSeconds())+'Z'
}

var d = new Date();
console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z

回答by Martin Braun

The new modern way to do this is to use toLocaleDateString, because it not just allows you to format a date with proper localization, you can even pass format options to archive the desired outcome:

新的现代方法是使用toLocaleDateString,因为它不仅允许您使用适当的本地化来格式化日期,您甚至可以传递格式选项来存档所需的结果:

var date = new Date(2018, 2, 1);
var result = date.toLocaleDateString("en-GB", { // you can skip the first argument
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
});
console.log(result);

When you skip the first argument it will detect the browser language, instead. Alternatively, you can use 2-digiton the year option, too.

当您跳过第一个参数时,它将检测浏览器语言。或者,您也可以使用2-digit年份选项。

If you don't need to support old browsers like IE10, this is the cleanest way to do the job. IE10 and lower versions won't understand the options argument.

如果您不需要支持像 IE10 这样的旧浏览器,这是完成这项工作的最干净的方式。IE10 及更低版本将无法理解 options 参数。

Note: Additionally, there is also toLocaleTimeString, if you want to localize or format the time of a date.

注意:此外,toLocaleTimeString如果您想本地化或格式化日期的时间,还有 。

回答by joan16v

You can define a "str_pad" function (as in php):

您可以定义一个“str_pad”函数(如在 php 中):

function str_pad(n) {
    return String("00" + n).slice(-2);
}

回答by Amin NAIRI

For you people from the future (ECMAScript 2017 and beyond)

为来自未来的人们(ECMAScript 2017 及以后)

Solution

解决方案

"use strict"

const today = new Date()

const year = today.getFullYear()

const month = `${today.getMonth() + 1}`.padStart(2, "0")

const day = `${today.getDate()}`.padStart(2, "0")

const stringDate = [day, month, year].join("/") // 13/12/2017

Explaination

说明

the String.prototype.padStart(targetLength[, padString])adds as many as possible padStringin the String.prototypetarget so that the new length of the target is targetLength.

String.prototype.padStart(targetLength[, padString])增加尽可能多的padStringString.prototype目标,使得目标的新长度是targetLength

Example

例子

"use strict"

let month = "9"

month = month.padStart(2, "0") // "09"

let byte = "00000100"

byte = byte.padStart(8, "0") // "00000100"

回答by kennebec

Number.prototype.padZero= function(len){
 var s= String(this), c= '0';
 len= len || 2;
 while(s.length < len) s= c + s;
 return s;
}

//in use:

//正在使用:

(function(){
 var myDate= new Date(), myDateString;
 myDate.setDate(myDate.getDate()+10);

 myDateString= [myDate.getDate().padZero(),
 (myDate.getMonth()+1).padZero(),
 myDate.getFullYear()].join('/');

 alert(myDateString);
})()

/*  value: (String)
09/09/2010
*/

回答by Povesma Dmytro

I found the shorterst way to do this:

我找到了最短的方法来做到这一点:

 MyDateString.replace(/(^|\D)(\d)(?!\d)/g, '');

will add leading zeros to all lonely, single digits

将为所有孤独的个位数添加前导零

回答by meaa

var MyDate = new Date();
var MyDateString = '';
MyDate.setDate(MyDate.getDate());
var tempoMonth = (MyDate.getMonth()+1);
var tempoDate = (MyDate.getDate());
if (tempoMonth < 10) tempoMonth = '0' + tempoMonth;
if (tempoDate < 10) tempoDate = '0' + tempoDate;
MyDateString = tempoDate + '/' + tempoMonth + '/' + MyDate.getFullYear();

回答by Hellojeffy

You could use ternary operator to format the date like an "if" statement.

您可以使用三元运算符将日期格式化为“if”语句。

For example:

例如:

var MyDate = new Date();
MyDate.setDate(MyDate.getDate()+10);
var MyDateString = (MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate()) + '/' + ((d.getMonth()+1) < 10 ? '0' + (d.getMonth()+1) : (d.getMonth()+1)) + '/' + MyDate.getFullYear();

So

所以

(MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate())

would be similar to an if statement, where if the getDate() returns a value less than 10, then return a '0' + the Date, or else return the date if greater than 10 (since we do not need to add the leading 0). Same for the month.

将类似于 if 语句,其中如果 getDate() 返回小于 10 的值,则返回“0”+ 日期,否则如果大于 10,则返回日期(因为我们不需要添加前导0)。同月。

Edit: Forgot that getMonth starts with 0, so added the +1 to account for it. Of course you could also just say d.getMonth() < 9 :, but I figured using the +1 would help make it easier to understand.

编辑:忘记了 getMonth 以 0 开头,所以添加了 +1 来解释它。当然,您也可以只说 d.getMonth() < 9 :,但我认为使用 +1 将有助于使其更容易理解。

回答by behnam shateri

There is another approach to solve this problem, using slicein JavaScript.

还有另一种方法可以解决这个问题,slice在 JavaScript 中使用。

var d = new Date();
var datestring = d.getFullYear() + "-" + ("0"+(d.getMonth()+1)).slice(-2) +"-"+("0" + d.getDate()).slice(-2);

the datestringreturn date with format as you expect: 2019-09-01

datestring返回日期格式如您所愿:2019年9月1日

another approach is using dateformatlibrary: https://github.com/felixge/node-dateformat

另一种方法是使用dateformat库:https: //github.com/felixge/node-dateformat