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.


Solution 1:

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"

Solution 2:

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 achieve 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.

Performance

If you plan to format a lot of dates, you should consider using Intl.DateTimeFormat instead:

var formatter = new Intl.DateTimeFormat("en-GB", { // <- re-use me
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
});
var date = new Date(2018, 2, 1);
var result = formatter.format(date);
console.log(result); // outputs “01/03/2018”

Historical dates

Years between 0 and 99 will be interpreted as 20th century years. To prevent this, initialize the date like so:

var date = new Date();
date.setFullYear(18, 2, 1); // the year is A.D. 18

Also years below 1000 will not contain leading zeros, because the formatter does not support 4-digit formatting at all. In this case you have to do manual formatting (see below).

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.

Historical dates

Years between 0 and 99 will also be interpreted as 20th century years. To prevent this, initialize the date like so:

var date = new Date();
date.setUTCFullYear(18, 2, 1); // the year is A.D. 18

Custom formatting with leading zeros on the year

Sadly, toLocaleDateString doesn't support leading zeros on the year. There is no 4-digit option.

Fortunately, the ISO format will always display at least 4 digits on the year. So, if you want to format historical dates below the year 1000 with leading zeros, you can fallback to a manual formatting approach using part of the ISO format method:

var date = new Date();
date.setUTCFullYear(18, 2, 1);
var ymd = date.toISOString().split('T')[0].split('-');
var result = `${ymd[2]}/${ymd[1]}/${ymd[0]}`;
console.log(result); // outputs “01/03/0018”

Miscellaneous

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

Solution 3:

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

Solution 4:

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"

Solution 5:

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

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