505

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

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.

John Slegers
  • 38,420
  • 17
  • 182
  • 152
Julian Coates
  • 5,079
  • 3
  • 13
  • 5

26 Answers26

1481

Try this: 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 last two characters of the string.

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.

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

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

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

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

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

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

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

("0" + "10").slice(-2)
"10"
user113716
  • 299,514
  • 60
  • 431
  • 433
  • 34
    Forked - date format YYYY-MM-DD http://jsfiddle.net/j6qJp/1/ It may be useful for somebody. Thanks – tomexx Oct 31 '12 at 13:59
  • 3
    Can someone explain why this is better than the answer that @Aleross provides below? It is not immediately clear what it does versus the pad function which is explicitly clear. – claudio Oct 29 '13 at 20:37
  • 1
    Simpler, just use myDate.toISOString() which has leading zeros. Parse out relevant parts using substring. – John Henckel Mar 28 '14 at 03:21
  • 1
    @n00b I agree. This is longer and seems like an overkill. Also, it looks worse in terms of performance (calling `slice` following a concatenation looks more expensive than a simple string concatenation following a comparison), but I am not a computer science graduate or anything like that. It is a creative solution, indeed, but nothing more than that, I think. – PhistucK Apr 01 '14 at 19:34
  • 1
    Way clever. Works fine for short, quick strings. Probably want to do something more performant if you were processing a lot of them. In a dragging display scenario, dragging and formatting across several date/time ticks and displaying them on the fly in a moving window - works just fine. – rickb Apr 01 '14 at 21:53
  • 2
    Not to mention that today this example gave me 26/06/2014 instead of 06/06/2014 – DazManCat Jun 06 '14 at 10:50
  • 3
    @DazManCat: That's what it is supposed to do. The code starts by adding 20 days to the current date. `MyDate.setDate(MyDate.getDate() + 20);` – cookie monster Jul 25 '14 at 16:45
  • 1
    @n00b I suppose it's not necessarily better, just more popular. I'm guessing if they are put side-by-side, it would be because of the additional private function required to perform the pad. – Phil Cooper Dec 17 '14 at 15:45
  • 3
    @n00b and @Phil Cooper, without getting hung up on a discussion about the ins and outs of timing JavaScript routines, I found that the `slice()` technique in the accepted answer is about a 1/10 of a second faster than @Aleross 's `pad()` technique on 1 million iterations. [jsFiddle](http://jsfiddle.net/ej4bb0oL/). "pay your money, take your pick". – Karl Nov 26 '15 at 14:32
  • 1
    `function pad(num) { return ("0"+num).slice(-2);}` – mplungjan Jan 04 '18 at 15:40
  • @claudio because there's no need to declare a function. – Tomas Gonzalez Jun 24 '19 at 15:19
  • awesome, thanks for the solution. – Puttamarigowda M S Feb 10 '21 at 15:00
118

Here is an example from the Date object docs on 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

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
Alex Ross
  • 3,589
  • 3
  • 23
  • 26
  • 4
    Very nice way of doing it. I think the accepted answer is really nice, but this even cleaner in my opinion – Binke Jan 19 '16 at 10:52
  • 1
    this could lead to unexpected bugs cause it outputs a string for < 10 and a number for >= 10 – David Fregoli Jun 23 '17 at 10:26
  • @DavidFregoli, all those date to string functions return a string, so if you input a string, `pad` does output only strings. – Rohmer Dec 03 '17 at 23:52
108

The modern way

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

var date = new Date(2018, 2, 1);
var result = date.toLocaleDateString("en-GB", { // you can use undefined as first argument
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
});
console.log(result); // outputs “01/03/2018”

When you use undefined as the first argument it will detect the browser language, instead. Alternatively, you can use 2-digit on the year option, too. Compatibility is good, IE won't play along, though.

For the ISO format

If you want to get your date in the YYYY-MM-DD format (ISO), the solution looks different:

var date = new Date(Date.UTC(2018, 2, 1));
var result = date.toISOString().split('T')[0];
console.log(result); // outputs “2018-03-01”

Your input date should be in the UTC format or toISOString() will fix that for you. This is done by using Date.UTC as shown above.

Miscellaneous

There is also toLocaleTimeString, that allows you to localize and format the time of a date.

Martin Braun
  • 5,873
  • 7
  • 43
  • 81
  • 6
    This is exactly what I was looking for, thanks. More info about the options available for toLocaleDateString here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString – JoseLinares Jul 25 '18 at 09:24
  • 1
    @JoseLinares Hi, thanks for putting this link back in the days. I just decided to improve my answer to make the solution more appealing for common scenarios, since you can skip the first argument and IE10 is not relevant anymore. With that in mind, I included your link into my answer. – Martin Braun Apr 12 '19 at 09:09
  • @modiX, sorry it was a my mistake in code and i took wrong way the description, Yes the *locales* (first variable) is *Optional*. – Kanhaiya lal Jul 03 '19 at 11:13
  • 1
    This should be the accepted answer. – TCSGrad Mar 13 '21 at 22:09
53

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

function str_pad(n) {
    return String("00" + n).slice(-2);
}
joan16v
  • 4,551
  • 2
  • 44
  • 45
51

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"
Amin NAIRI
  • 1,521
  • 14
  • 16
  • 4
    This is part of ES2017 or ES8. So it's incorrect to say "ES6+" as it's not part of ES6 and ES7. – Noel Llevares Jan 08 '18 at 01:43
  • 1
    This should technically be `.padStart(2, '0')` since the second parameter is a string, although it probably won't matter unless you're using TypeScript – bmaupin Apr 17 '20 at 13:14
14

I found the shorterst way to do this:

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

will add leading zeros to all lonely, single digits

Povesma Dmytro
  • 151
  • 1
  • 5
  • I like this solution, can you maybe clarifiy a bit what happens there? – Gobliins Aug 08 '19 at 10:19
  • Could you please explain how this works? Seems like an elegant solution – SeaWarrior404 Nov 03 '20 at 04:07
  • 1
    Regexp finds maximum of three groups: $1 - any non-digit symbol (or beginning of the line) $2 - any digit $3 - any non-digit (that may not exist) Then we're replacing the captured (matched) stuff with $1 + "0" + $2 which comes $10$2 in the replacement string. – Povesma Dmytro Nov 10 '20 at 21:13
  • It finds a single digit (between any other symbols) and adds a zero before this single digit You can play with S = ['1/2/16', '2.10.20', '3 5 9', 'Today is 4.5.20', 'US style 3/9/21']; S.forEach(s => console.log(s.replace(/(^|\D)(\d)(?!\d)/g, '$10$2'))) – Povesma Dmytro Nov 10 '20 at 21:22
12
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
*/
kennebec
  • 94,076
  • 30
  • 99
  • 125
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();
meaa
  • 81
  • 1
  • 1
6

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

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.

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.

Hellojeffy
  • 1,702
  • 1
  • 18
  • 23
6

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

Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
behnam shateri
  • 665
  • 7
  • 17
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));
DebanjanB
  • 118,661
  • 30
  • 168
  • 217
MJ55
  • 243
  • 2
  • 11
3
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();
}
StealthRT
  • 9,252
  • 35
  • 155
  • 302
Alex
  • 31
  • 2
3

I wrapped the correct answer of this question in a function that can add multiple leading zero's but defaults to adding 1 zero.

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

for working with numbers only and not more than 2 digits, this is also an approach:

function zeroFill(i) {
    return (i < 10 ? '0' : '') + i
  }
Robbie Bardijn
  • 405
  • 2
  • 6
1

What I would do, is create my own custom Date helper that looks like this :

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

(see also this Fiddle)

John Slegers
  • 38,420
  • 17
  • 182
  • 152
1

Another option, using a built-in function to do the padding (but resulting in quite long code!):

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

// '12/06/2017'

And another, manipulating strings with regular expressions:

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

// '2017/06/12'

But be aware that one will show the year at the start and the day at the end.

joeytwiddle
  • 24,338
  • 11
  • 107
  • 91
1

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"})
francis
  • 35
  • 6
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();
};
vishu2124
  • 2,463
  • 1
  • 11
  • 8
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);
Vikas Kandari
  • 736
  • 9
  • 20
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();
0

The following aims to extract configuration, hook into Date.protoype and apply configuration.

I've used an Array to store time chunks and when I push() this as a Date object, it returns me the length to iterate. When I'm done, I can use join on the return value.

This seems to work pretty fast: 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();

demo: http://jsfiddle.net/tive/U4MZ3/

Tim Vermaelen
  • 6,001
  • 1
  • 22
  • 36
0

Add some padding to allow a leading zero - where needed - and concatenate using your delimiter of choice as string.

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('/');
TV-C-15
  • 653
  • 1
  • 9
  • 14
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}`);
Mario
  • 4,117
  • 1
  • 22
  • 39
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
  }
Deaner
  • 1
  • 1
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())}`);
leopal
  • 3,570
  • 1
  • 23
  • 29
  • 2
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – leopal Jan 10 '20 at 14:20
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
j3ff
  • 4,539
  • 5
  • 35
  • 45
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.

Nikolas Charalambidis
  • 29,749
  • 7
  • 67
  • 124