Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get Month and Date of JavaScript in 2 digit format?

Tags:

javascript

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?

like image 669
srini Avatar asked May 18 '11 06:05

srini


People also ask

What is JavaScript default Date format?

The string format should be: YYYY-MM-DDTHH:mm:ss. sssZ , where: YYYY-MM-DD – is the date: year-month-day. The character "T" is used as the delimiter.

What does the JavaScript Date () function do?

Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of date objects, using either local time or UTC (universal, or GMT) time.

Is there a Date type in JavaScript?

JavaScript does not have a date data type. However, you can use the Date object and its methods to work with dates and times in your applications. The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.


2 Answers

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

for the date, and similar:

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

for the month.

like image 54
Hugo Avatar answered Sep 21 '22 10:09

Hugo


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

I hope this helps

like image 42
Qiniso Avatar answered Sep 22 '22 10:09

Qiniso