546

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

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

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

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

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

如果有人可以告诉我将这些插入脚本的位置,我将不胜感激。

4

30 回答 30

1548

试试这个: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();

编辑:

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

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

因此,如果MyDate.getMonth()返回9,它将是:

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

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

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

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

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

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

("0" + "10").slice(-2)
"10"
于 2010-08-31T00:39:18.177 回答
178
于 2017-11-07T14:38:00.900 回答
123

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

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

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

/* 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
于 2012-09-23T06:47:40.527 回答
61

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

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 padString in the String.prototype target so that the new length of the target is targetLength.

Example

"use strict"

let month = "9"

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

let byte = "00000100"

byte = byte.padStart(8, "0") // "00000100"
于 2017-12-12T13:43:22.637 回答
55

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

function str_pad(n) {
    return String("00" + n).slice(-2);
}
于 2015-03-12T13:17:53.640 回答
14

我找到了最简单的方法:

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

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

于 2017-09-05T09:14:50.950 回答
12
Number.prototype.padZero= function(len){
 var s= String(this), c= '0';
 len= len || 2;
 while(s.length < len) s= c + s;
 return s;
}

//正在使用:

(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
*/
于 2010-08-31T02:17:09.007 回答
8
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();
于 2012-07-15T08:03:00.097 回答
7

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

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

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

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

于 2019-09-01T18:03:53.697 回答
6

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

例如:

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();

所以

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

类似于 if 语句,如果 getDate() 返回的值小于 10,则返回 '0' + 日期,否则如果大于 10,则返回日期(因为我们不需要添加前导0)。这个月也一样。

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

于 2014-03-13T21:24:46.593 回答
5

Nowadays you can also utilize String.prototype.padStart to reach the goal in quick and easy way

String(new Date().getMonth() + 1).padStart(2, '0')

The availability can be assessed at caniuse

var date = new Date()

var year = date.getFullYear()
var month = String(date.getMonth() + 1).padStart(2, '0')
var day = String(date.getDate()).padStart(2, '0')

console.log('%s/%s/%s', month, day, year)

Check

var date = new Date('7/4/2021')
    
var year = date.getFullYear()
var month = String(date.getMonth() + 1).padStart(2, '0')
var day = String(date.getDate()).padStart(2, '0')
    
/**
 * Expected output: 07/04/2021
 */
console.log('%s/%s/%s', month, day, year)

Polyfill for old browsers

String.prototype.padStart || Object.defineProperty(String.prototype, 'padStart', {
    configurable : true,
    writable : true,
    value : function (targetLength, padString) {
        'use strict'
        /**
         * String.prototype.padStart polyfill
         * https://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date
         */
        targetLength = targetLength | 0
        padString = arguments.length > 1 ? String(padString) : ' '

        if (this.length < targetLength && padString.length) {
            targetLength = targetLength - this.length

            while (padString.length < targetLength) {
                padString += padString
            }

            return padString.slice(0, targetLength) + this
        } else {
            return this
        }
    }
})
于 2021-09-16T09:57:14.477 回答
4
function formatDate(jsDate){
  // add leading zeroes to jsDate when days or months are < 10.. 
  // i.e.
  //     formatDate(new Date("1/3/2013")); 
  // returns
  //    "01/03/2103"
  ////////////////////
  return (jsDate.getDate()<10?("0"+jsDate.getDate()):jsDate.getDate()) + "/" + 
      ((jsDate.getMonth()+1)<10?("0"+(jsDate.getMonth()+1)):(jsDate.getMonth()+1)) + "/" + 
      jsDate.getFullYear();
}
于 2013-03-02T22:00:02.770 回答
4

You can provide options as a parameter to format date. First parameter is for locale which you might not need and second is for options. For more info visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

var date = new Date(Date.UTC(2012, 1, 1, 3, 0, 0));
var options = { year: 'numeric', month: '2-digit', day: '2-digit' };
console.log(date.toLocaleDateString(undefined,options));
于 2019-03-07T08:48:08.960 回答
3

我将这个问题的正确答案包装在一个可以添加多个前导零但默认添加 1 个零的函数中。

function zeroFill(nr, depth){
  depth = (depth === undefined)? 1 : depth;

  var zero = "0";
  for (var i = 0; i < depth; ++i) {
    zero += "0";
  }

  return (zero + nr).slice(-(depth + 1));
}

对于仅使用数字且不超过 2 位的数字,这也是一种方法:

function zeroFill(i) {
    return (i < 10 ? '0' : '') + i
  }
于 2014-05-17T16:40:31.630 回答
2

Adding on to @modiX answer, this is what works...DO NOT LEAVE THAT as empty

today.toLocaleDateString("default", {year: "numeric", month: "2-digit", day: "2-digit"})
于 2019-05-06T02:40:31.850 回答
1

我要做的是创建我自己的自定义日期助手,如下所示:

var DateHelper = {
    addDays : function(aDate, numberOfDays) {
        aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays
        return aDate;                                  // Return the date
    },
    format : function format(date) {
        return [
           ("0" + date.getDate()).slice(-2),           // Get day and pad it with zeroes
           ("0" + (date.getMonth()+1)).slice(-2),      // Get month and pad it with zeroes
           date.getFullYear()                          // Get full year
        ].join('/');                                   // Glue the pieces together
    }
}

// With this helper, you can now just use one line of readable code to :
// ---------------------------------------------------------------------
// 1. Get the current date
// 2. Add 20 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));

(另见这个小提琴

于 2016-03-09T14:39:32.470 回答
1

另一种选择,使用内置函数进行填充(但会导致代码很长!):

myDateString = myDate.getDate().toLocaleString('en-US', {minimumIntegerDigits: 2})
  + '/' + (myDate.getMonth()+1).toLocaleString('en-US', {minimumIntegerDigits: 2})
  + '/' + myDate.getFullYear();

// '12/06/2017'

另一个,用正则表达式操作字符串:

var myDateString = myDate.toISOString().replace(/T.*/, '').replace(/-/g, '/');

// '2017/06/12'

但请注意,将在开始时显示年份,在结束时显示日期。

于 2017-06-12T03:46:19.607 回答
1

try this for a basic function, no libraries required

Date.prototype.CustomformatDate = function() {
 var tmp = new Date(this.valueOf());
 var mm = tmp.getMonth() + 1;
 if (mm < 10) mm = "0" + mm;
 var dd = tmp.getDate();
 if (dd < 10) dd = "0" + dd;
 return mm + "/" + dd + "/" + tmp.getFullYear();
};
于 2019-09-04T15:06:45.860 回答
1

Here is very simple example how you can handle this situation.

var mydate = new Date();

var month = (mydate.getMonth().toString().length < 2 ? "0"+mydate.getMonth().toString() :mydate.getMonth());

var date = (mydate.getDate().toString().length < 2 ? "0"+mydate.getDate().toString() :mydate.getDate());

var year = mydate.getFullYear();

console.log("Format Y-m-d : ",year+"-"+month+"-" + date);

console.log("Format Y/m/d : ",year+"/"+month+"/" + date);

于 2019-11-17T20:55:55.700 回答
1

You could simply use :

const d = new Date();
const day = `0${d.getDate()}`.slice(-2);

So a function could be created like :

AddZero(val){
    // adding 0 if the value is a single digit
    return `0${val}`.slice(-2);
}

Your new code :

var MyDate = new Date();
var MyDateString = new Date();

MyDate.setDate(MyDate.getDate()+10);
MyDateString = AddZero(MyDate.getDate()) + '/' + AddZero(MyDate.getMonth() + 1) + '/' + MyDate.getFullYear();
于 2020-11-02T09:12:30.877 回答
1

toISOString can get leading 0

    const currentdate = new Date(); 
    const date = new Date(Date.UTC(currentdate.getFullYear(), (currentdate.getMonth()),currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), currentdate.getSeconds()));
    //you can pass YY, MM, DD //op: 2018-03-01
    //i have passed YY, MM, DD, HH, Min, Sec // op : 2021-06-09T12:14:27.000Z
    console.log(date.toISOString());

output will be similar to this : 2021-06-09T12:14:27.000Z

于 2021-06-09T06:49:12.867 回答
1

I think this solution is easier and can be easily remembered:

var MyDate = new Date();


var day = MyDate.getDate() + 10; // 10 days in advance
var month = MyDate.getMonth() + 1; // since months start from 0 we should add 1 to it
var year = MyDate.getFullYear();

day = checkDate(day);
month = checkDate(month);


function checkDate(i){
    if(i < 10){
    i = '0' + i;
  }
  return i;
}

console.log(`${month}/${day}/${year}`);

于 2021-08-01T18:31:07.360 回答
0

以下旨在提取配置、挂钩Date.protoype和应用配置。

我用一个Array来存储时间块,当我push() this作为一个Date对象时,它返回我迭代的长度。完成后,我可以使用joinreturn值。

这似乎工作得很快:0.016ms

// Date protoype
Date.prototype.formatTime = function (options) {
    var i = 0,
        time = [],
        len = time.push(this.getHours(), this.getMinutes(), this.getSeconds());

    for (; i < len; i += 1) {
        var tick = time[i];
        time[i] = tick < 10 ? options.pad + tick : tick;
    }

    return time.join(options.separator);
};

// Setup output
var cfg = {
    fieldClock: "#fieldClock",
    options: {
        pad: "0",
        separator: ":",
        tick: 1000
    }
};

// Define functionality
function startTime() {
    var clock = $(cfg.fieldClock),
        now = new Date().formatTime(cfg.options);

    clock.val(now);
    setTimeout(startTime, cfg.options.tick);
}

// Run once
startTime();

演示:http: //jsfiddle.net/tive/U4MZ3/

于 2013-05-01T07:44:16.220 回答
0

添加一些填充以允许前导零 - 如果需要 - 并使用您选择的分隔符作为字符串连接。

Number.prototype.padLeft = function(base,chr){
        var  len = (String(base || 10).length - String(this).length)+1;
        return len > 0? new Array(len).join(chr || '0')+this : this;
    }

var d = new Date(my_date);
var dformatted = [(d.getMonth()+1).padLeft(), d.getDate().padLeft(), d.getFullYear()].join('/');
于 2017-10-05T21:45:35.923 回答
0

As @John Henckel suggests, starting using the toISOString() method makes things easier

const dateString = new Date().toISOString().split('-');
const year = dateString[0];
const month = dateString[1];
const day = dateString[2].split('T')[0];

console.log(`${year}-${month}-${day}`);

于 2019-02-25T16:06:00.727 回答
0
 let date = new Date();
 let dd = date.getDate();//day of month

 let mm = date.getMonth();// month
 let yyyy = date.getFullYear();//day of week
 if (dd < 10) {//if less then 10 add a leading zero
     dd = "0" + dd;
   }
 if (mm < 10) {
    mm = "0" + mm;//if less then 10 add a leading zero
  }
于 2019-05-15T22:49:43.793 回答
0
function pad(value) {
    return value.tostring().padstart(2, 0);
}

let d = new date();
console.log(d);
console.log(`${d.getfullyear()}-${pad(d.getmonth() + 1)}-${pad(d.getdate())}t${pad(d.gethours())}:${pad(d.getminutes())}:${pad(d.getseconds())}`);
于 2020-01-10T13:16:45.503 回答
0

You can use String.slice() which extracts a section of a string and returns it as a new string, without modifying the original string:

const currentDate = new Date().toISOString().slice(0, 10) // 2020-04-16

Or you can also use a lib such as Moment.js to format the date:

const moment = require("moment")
const currentDate = moment().format("YYYY-MM-DD") // 2020-04-16
于 2020-04-16T14:57:43.303 回答
0

A simple dateformat library saved my life (GitHub):

  • Node.js: var dateFormat = require("dateformat");
  • ES6: import dateFormat from "dateformat";
const now = new Date();             // consider 3rd of December 1993

const full = dateFormat(today, "yyyy-mm-dd");  // 1993-12-03
const day = dateFormat(today, "dd");           // 03
const month = dateFormat(today, "mm");         // 12
const year = dateFormat(today, "yyyy");        // 1993

It's worth to mention it supports a wide range of mask options.

于 2021-03-07T18:53:43.193 回答
-1
const month = date.toLocaleDateString('en-US', { month: '2-digit' });
const day = date.toLocaleDateString('en-US', { day: '2-digit' });
const year = date.getFullYear();
const dateString = `${month}-${day}-${year}`;
于 2021-08-14T04:39:46.167 回答