449

When we call getMonth() and getDate() on date object, we will get the single digit number. For example :

For january, it displays 1, but I need to display it as 01. How to do that?

mike
  • 4,929
  • 4
  • 40
  • 80
srini
  • 6,719
  • 8
  • 32
  • 36
  • 2
    http://stackoverflow.com/questions/2998784/how-to-output-integers-with-leading-zeros-in-javascript – carlosfigueira May 18 '11 at 06:10
  • Please see https://stackoverflow.com/questions/6040515/how-do-i-get-month-and-date-of-javascript-in-2-digit-format#answer-51863005 – Aaron Jan 15 '20 at 14:17

32 Answers32

1020
("0" + this.getDate()).slice(-2)

for the date, and similar:

("0" + (this.getMonth() + 1)).slice(-2)

for the month.

Mr.Wizard
  • 24,179
  • 5
  • 44
  • 125
Hugo
  • 10,281
  • 1
  • 15
  • 6
  • 99
    Cool, but: `function addZ(n){return n<10? '0'+n:''+n;}` is a bit more generic. – RobG May 18 '11 at 06:19
  • 11
    slice is clever, but it's much slower than a simple comparison: http://jsperf.com/slice-vs-comparison – dak May 16 '12 at 03:25
  • 35
    @dak: And when is that realistically going to matter? I doubt you're calculating the month thousands of times a second. – Sasha Chedygov Jul 02 '12 at 17:01
  • 1
    @RobG doesn't work for strings. It pads an extra zero when you pass it '01'. The above answer works even in this scenario. – Kasper Holdum Jul 20 '12 at 12:46
  • 2
    @KasperHoldum–`getMonth` and `getDate` return numbers, not strings. And if compatibility with Strings is required, then `'0' + Number(n)` will do the job. – RobG Jul 23 '12 at 00:16
  • 2
    @SashaChedygov unless, for example, one is animating a map using openlayers, you would generally be right. never assume, though. i found dak's comment very useful because i ran into exactly this problem. – tony gil Feb 19 '13 at 16:30
  • 11
    @Sasha Chedygov sure you might calculate the month thousands of times a second, particularly if you are sorting – Dexygen Dec 02 '13 at 18:25
  • @George Jempty. If you let the server do the sort that won't be a issue. – Jens Alenius Sep 13 '17 at 15:26
  • 8
    Why not use [`padStart`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart)? – SomeGuyOnAComputer Jun 08 '18 at 23:15
  • 1
    Can you please explain this a little bit. Because I'm using your solution so I'll have to explain this to my tech lead. She may cross-question me. Just tell me why `slice(-2)`. – Tanzeel Feb 05 '20 at 05:50
  • 1
    Also possible with `substr` instead of `slice`, for instance `("0" + this.getDate()).substr(-2)` – morbac Mar 03 '21 at 13:18
  • This turns the value into a string, adds a "0" to the front, and then takes the last two digits. So if the value was already two digits, you just get those, but if it was only one, you get a leading 0 added. – Mark Reed Jul 17 '21 at 23:07
  • padStart is no supported in ie. – horoyoi o Jan 10 '22 at 04:20
116

If you want a format like "YYYY-MM-DDTHH:mm:ss", then this might be quicker:

var date = new Date().toISOString().substr(0, 19);
// toISOString() will give you YYYY-MM-DDTHH:mm:ss.sssZ

Or the commonly used MySQL datetime format "YYYY-MM-DD HH:mm:ss":

var date2 = new Date().toISOString().substr(0, 19).replace('T', ' ');
starball
  • 20,030
  • 7
  • 43
  • 238
Qiniso
  • 2,587
  • 1
  • 24
  • 30
  • 1
    This is the tersest solution I have come across. Only issue here is that of the timezone offset. – Praym Aug 26 '16 at 15:22
  • 5
    Timezone offset could be taken care of with something like: var date = new Date(new Date().getTime() - new Date().getTimezoneOffset()*60*1000).toISOString().substr(0,19).replace('T', ' '); – Praym Aug 26 '16 at 15:47
  • Praym, your code works for me, but copy and paste must have had some hidden character or something, so I just hand typed it. – spacebread Jun 09 '17 at 20:50
  • I ended up on this question trying to solve this exact problem so, as it turns out, your answer is what I needed. – Engineer Toast Jun 30 '17 at 15:30
  • 1
    Note that this method will return the date and time according to the UTC timezone. – Amr Dec 02 '18 at 06:27
106

Why not use padStart ?

padStart(targetLength, padString) where

  • targetLength is 2
  • padString is 0

// Source: https://stackoverflow.com/a/50769505/2965993

var dt = new Date();

year  = dt.getFullYear();
month = (dt.getMonth() + 1).toString().padStart(2, "0");
day   = dt.getDate().toString().padStart(2, "0");

console.log(year + '/' + month + '/' + day);

This will always return 2 digit numbers even if the month or day is less than 10.

Notes:

  • This will only work with Internet Explorer if the js code is transpiled using babel.
  • getFullYear() returns the 4 digit year and doesn't require padStart.
  • getMonth() returns the month from 0 to 11.
    • 1 is added to the month before padding to keep it 1 to 12.
  • getDate() returns the day from 1 to 31.
    • The 7th day will return 07 and so we do not need to add 1 before padding the string.
SomeGuyOnAComputer
  • 5,414
  • 6
  • 40
  • 72
49

Example for month:

function getMonth(date) {
  var month = date.getMonth() + 1;
  return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}  

You can also extend Date object with such function:

Date.prototype.getMonthFormatted = function() {
  var month = this.getMonth() + 1;
  return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
Seth
  • 10,198
  • 10
  • 45
  • 68
Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153
  • 5
    Note that getMonth returns a number between 0 and 11, not 1 and 12. – Salman A May 18 '11 at 06:11
  • 4
    This returns inconsistent results. For November and December it returns a string and for other months it returns a number. – Tim Down May 18 '11 at 08:59
  • I updated the code to implement Salman A warning that getMonth is zero based instead of 1. And added quotes to make sure a string is always returned. – Jan Derk May 18 '15 at 18:53
34

The best way to do this is to create your own simple formatter (as below):

getDate() returns the day of the month (from 1-31)
getMonth() returns the month (from 0-11) < zero-based, 0=January, 11=December
getFullYear() returns the year (four digits) < don't use getYear()

function formatDateToString(date){
   // 01, 02, 03, ... 29, 30, 31
   var dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
   // 01, 02, 03, ... 10, 11, 12
   var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
   // 1970, 1971, ... 2015, 2016, ...
   var yyyy = date.getFullYear();

   // create the format you want
   return (dd + "-" + MM + "-" + yyyy);
}
Seth
  • 10,198
  • 10
  • 45
  • 68
Marcel
  • 1,494
  • 1
  • 23
  • 33
26

I would do this:

var date = new Date(2000, 0, 9);
var str = new Intl.DateTimeFormat('en-US', {
  month: '2-digit',
  day: '2-digit',
  year: 'numeric'
}).format(date);

console.log(str); // prints "01/09/2000"
SomeGuyOnAComputer
  • 5,414
  • 6
  • 40
  • 72
Fernando Vezzali
  • 2,219
  • 1
  • 29
  • 32
  • Great. I wasn't understanding at first what to pass in options parameter of toLocaleDateString to get this. Your answer helped. I also found this MDN doc which has all the other option values for those who may need a different formatting - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat – thisisashwani Dec 24 '20 at 08:54
  • One downside of this approach is that you cannot rearrange the date easily e.g. `2000/09/01` – SomeGuyOnAComputer Apr 22 '23 at 00:55
12

The following is used to convert db2 date format i.e YYYY-MM-DD using ternary operator

var currentDate = new Date();
var twoDigitMonth=((currentDate.getMonth()+1)>=10)? (currentDate.getMonth()+1) : '0' + (currentDate.getMonth()+1);  
var twoDigitDate=((currentDate.getDate())>=10)? (currentDate.getDate()) : '0' + (currentDate.getDate());
var createdDateTo = currentDate.getFullYear() + "-" + twoDigitMonth + "-" + twoDigitDate; 
alert(createdDateTo);
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
9

Just another example, almost one liner.

var date = new Date();
console.log( (date.getMonth() < 9 ? '0': '') + (date.getMonth()+1) );
Andrés
  • 256
  • 4
  • 8
7
function monthFormated(date) {
   //If date is not passed, get current date
   if(!date)
     date = new Date();

     month = date.getMonth();

    // if month 2 digits (9+1 = 10) don't add 0 in front 
    return month < 9 ? "0" + (month+1) : month+1;
}
Seth
  • 10,198
  • 10
  • 45
  • 68
ssamuel68
  • 932
  • 13
  • 10
7

If it might spare some time I was looking to get:

YYYYMMDD

for today, and got along with:

const dateDocumentID = new Date()
  .toISOString()
  .substr(0, 10)
  .replace(/-/g, '');
Yassine S.
  • 1,061
  • 1
  • 13
  • 22
  • 2
    The answer is neat. For `DD/MM/YY`, I went to `new Date().toISOString().substr(0, 10).split('-').reverse().map(x => x.substr(0, 2)).join('/')` – Max Ma Jul 01 '19 at 05:00
6

Using Moment.js it can be done like that:

moment(new Date(2017, 1, 1)).format('DD') // day
moment(new Date(2017, 1, 1)).format('MM') // month
Aliaksandr Sushkevich
  • 11,550
  • 7
  • 37
  • 44
6
function monthFormated() {
  var date = new Date(),
      month = date.getMonth();
  return month+1 < 10 ? ("0" + month) : month;
}
Enamul Hassan
  • 5,266
  • 23
  • 39
  • 56
Mohsen
  • 64,437
  • 34
  • 159
  • 186
5

This was my solution:

function leadingZero(value) {
  if (value < 10) {
    return "0" + value.toString();
  }
  return value.toString();
}

var targetDate = new Date();
targetDate.setDate(targetDate.getDate());
var dd = targetDate.getDate();
var mm = targetDate.getMonth() + 1;
var yyyy = targetDate.getFullYear();
var dateCurrent = leadingZero(mm) + "/" + leadingZero(dd) + "/" + yyyy;
Seth
  • 10,198
  • 10
  • 45
  • 68
Jon
  • 51
  • 1
  • 1
5

Ternary Operator Solution

A simple ternary operator can add a "0" before the number if the month or day is less than 10 (assuming you need this information for use in a string).

let month = (date.getMonth() < 10) ? "0" + date.getMonth().toString() : date.getMonth();
let day = (date.getDate() < 10) ? "0" + date.getDate().toString() : date.getDate();
Matthew Rideout
  • 7,330
  • 2
  • 42
  • 61
5
const today = new Date().toISOString()
const fullDate = today.split('T')[0];
console.log(fullDate) //prints YYYY-MM-DD
  • 1
    toISOString() converts the date from the computer timezone to UTC timezone, so if you are in Europe, date 2021-01-01(T00:00) is printed as 2020-12-31(T23:00) :/ – Honza Jun 02 '21 at 13:27
4

Not an answer but here is how I get the date format I require in a variable

function setDateZero(date){
  return date < 10 ? '0' + date : date;
}

var curr_date = ev.date.getDate();
var curr_month = ev.date.getMonth() + 1;
var curr_year = ev.date.getFullYear();
var thisDate = curr_year+"-"+setDateZero(curr_month)+"-"+setDateZero(curr_date);

Hope this helps!

Seth
  • 10,198
  • 10
  • 45
  • 68
foxybagga
  • 4,184
  • 2
  • 34
  • 31
4

The more modern approach perhaps, using "padStart"

const now = new Date();
const day = `${now.getDate()}`.padStart(2, '0');
const month = `${now.getMonth()}`.padStart(2, '0');
const year = now.getFullYear();

then you can build as a template string if you wish:

`${day}/${month}/${year}`
4

How it easy?

new Date().toLocaleString("en-US", { day: "2-digit" })

Another options are available such:

  • weekday
  • year
  • month

More info here. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString#using_options

  • OP wanted month and date this only gives the date – Matthew Barlowe Oct 01 '21 at 19:19
  • use this: new Date().toLocaleString("en-US", { day: "2-digit",month: 'long',year: 'numeric' }), read this for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString#using_options – Akram Ashraf Nov 04 '21 at 11:31
  • 1
    Edit the question instead of posting in the comments please makes it easier for people to read use it in the future – Matthew Barlowe Nov 04 '21 at 20:42
3

Tip from MDN :

function date_locale(thisDate, locale) {
  if (locale == undefined)
    locale = 'fr-FR';
  // set your default country above (yes, I'm french !)
  // then the default format is "dd/mm/YYY"

  if (thisDate == undefined) {
    var d = new Date();
  } else {
    var d = new Date(thisDate);
  }
  return d.toLocaleDateString(locale);
}

var thisDate = date_locale();
var dayN = thisDate.slice(0, 2);
var monthN = thisDate.slice(3, 5);
console.log(dayN);
console.log(monthN);

http://jsfiddle.net/v4qcf5x6/

Seth
  • 10,198
  • 10
  • 45
  • 68
Glaubule
  • 169
  • 1
  • 7
3

new Date().getMonth() method returns the month as a number (0-11)

You can get easily correct month number with this function.

function monthFormatted() {
  var date = new Date(),
      month = date.getMonth();
  return month+1 < 10 ? ("0" + month) : month;
}
pushkin
  • 9,575
  • 15
  • 51
  • 95
3

I would suggest you use a different library called Moment https://momentjs.com/

This way you are able to format the date directly without having to do extra work

const date = moment().format('YYYY-MM-DD')
// date: '2020-01-04'

Make sure you import moment as well to be able to use it.

yarn add moment 
# to add the dependency
import moment from 'moment' 
// import this at the top of the file you want to use it in

Hope this helps :D

  • 1
    Moment.js has already been suggested; but your advice is still complete and useful. – iND Jan 05 '20 at 02:15
2
function GetDateAndTime(dt) {
  var arr = new Array(dt.getDate(), dt.getMonth(), dt.getFullYear(),dt.getHours(),dt.getMinutes(),dt.getSeconds());

  for(var i=0;i<arr.length;i++) {
    if(arr[i].toString().length == 1) arr[i] = "0" + arr[i];
  }

  return arr[0] + "." + arr[1] + "." + arr[2] + " " + arr[3] + ":" + arr[4] + ":" + arr[5]; 
}
Seth
  • 10,198
  • 10
  • 45
  • 68
2

The answers here were helpful, however I need more than that: not only month, date, month, hours & seconds, for a default name.

Interestingly, though prepend of "0" was needed for all above, " + 1" was needed only for month, not others.

As example:

("0" + (d.getMonth() + 1)).slice(-2)     // Note: +1 is needed
("0" + (d.getHours())).slice(-2)         // Note: +1 is not needed
Matt
  • 74,352
  • 26
  • 153
  • 180
Manohar Reddy Poreddy
  • 25,399
  • 9
  • 157
  • 140
2

And another version here https://jsfiddle.net/ivos/zcLxo8oy/1/, hope to be useful.

var dt = new Date(2016,5,1); // just for the test
var separator = '.';
var strDate = (dt.getFullYear() + separator + (dt.getMonth() + 1) + separator + dt.getDate());
// end of setup

strDate = strDate.replace(/(\b\d{1}\b)/g, "0$1")
i100
  • 4,529
  • 1
  • 22
  • 20
1

My solution:

function addLeadingChars(string, nrOfChars, leadingChar) {
    string = string + '';
    return Array(Math.max(0, (nrOfChars || 2) - string.length + 1)).join(leadingChar || '0') + string;
}

Usage:

var
    date = new Date(),
    month = addLeadingChars(date.getMonth() + 1),
    day = addLeadingChars(date.getDate());

jsfiddle: http://jsfiddle.net/8xy4Q/1/

user3336882
  • 3,083
  • 2
  • 15
  • 13
1
var net = require('net')

function zeroFill(i) {
  return (i < 10 ? '0' : '') + i
}

function now () {
  var d = new Date()
  return d.getFullYear() + '-'
    + zeroFill(d.getMonth() + 1) + '-'
    + zeroFill(d.getDate()) + ' '
    + zeroFill(d.getHours()) + ':'
    + zeroFill(d.getMinutes())
}

var server = net.createServer(function (socket) {
  socket.end(now() + '\n')
})

server.listen(Number(process.argv[2]))
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
1

if u want getDate() function to return the date as 01 instead of 1, here is the code for it.... Lets assume Today's date is 01-11-2018

var today = new Date();
today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + today.getDate();      
console.log(today);       //Output: 2018-11-1


today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + ((today.getDate() < 10 ? '0' : '') + today.getDate());
console.log(today);        //Output: 2018-11-01
Jayanth G
  • 69
  • 1
  • 4
1

I wanted to do something like this and this is what i did

p.s. i know there are right answer(s) on top, but just wanted to add something of my own here

const todayIs = async () =>{
    const now = new Date();
    var today = now.getFullYear()+'-';
    if(now.getMonth() < 10)
        today += '0'+now.getMonth()+'-';
    else
        today += now.getMonth()+'-';
    if(now.getDay() < 10)
        today += '0'+now.getDay();
    else
        today += now.getDay();
    return today;
}
Mohid Kazi
  • 84
  • 1
  • 5
1

If you'll check smaller than 10, you haven't to create a new function for that. Just assign a variable into brackets and return it with ternary operator.

(m = new Date().getMonth() + 1) < 10 ? `0${m}` : `${m}`
sametcodes
  • 583
  • 5
  • 8
1
currentDate(){
        var today = new Date();
        var dateTime =  today.getFullYear()+'-'+
                        ((today.getMonth()+1)<10?("0"+(today.getMonth()+1)):(today.getMonth()+1))+'-'+
                        (today.getDate()<10?("0"+today.getDate()):today.getDate())+'T'+
                        (today.getHours()<10?("0"+today.getHours()):today.getHours())+ ":" +
                        (today.getMinutes()<10?("0"+today.getMinutes()):today.getMinutes())+ ":" +
                        (today.getSeconds()<10?("0"+today.getSeconds()):today.getSeconds());        
            return dateTime;
},
Arun Verma
  • 11
  • 2
0
$("body").delegate("select[name='package_title']", "change", function() {

    var price = $(this).find(':selected').attr('data-price');
    var dadaday = $(this).find(':selected').attr('data-days');
    var today = new Date();
    var endDate = new Date();
    endDate.setDate(today.getDate()+parseInt(dadaday));
    var day = ("0" + endDate.getDate()).slice(-2)
    var month = ("0" + (endDate.getMonth() + 1)).slice(-2)
    var year = endDate.getFullYear();

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

    $('#price_id').val(price);
    $('#date_id').val(someFormattedDate);
});
kyun
  • 9,710
  • 9
  • 31
  • 66
sbcharya
  • 1
  • 1
0

date-fns.

import { lightFormat } from 'date-fns';
lightFormat(new Date(), 'dd');
alextes
  • 1,817
  • 2
  • 15
  • 22