Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding 0 to months in jQuery date

I have a jQuery script which returns the current date into a text box. However, when a month with only one digit is displayed (e.g. 8) I want it to place a 0 before it (e.g. 08) and not place a 0 before it if it has 2 digits (e.g. 11).

How can I do this? I hope you can understand my question. Here is my jQuery code:

var myDate = new Date();
var prettyDate =myDate.getDate() + '' + (myDate.getMonth()+1) + '' + myDate.getFullYear();
$("#date").val(prettyDate);
like image 217
Callum Whyte Avatar asked Aug 11 '11 00:08

Callum Whyte


People also ask

How to add 0 in date in JavaScript?

var MyDate = new Date(); var MyDateString; MyDate. setDate(MyDate. getDate() + 20); MyDateString = ('0' + MyDate. getDate()).

How to add 0 in front of time in JavaScript?

Use the String() object to convert the number to a string. Call the padStart() method to add zeros to the start of the string. The padStart method will return a new, padded with leading zeros string.

How do you format a date?

Press CTRL+1. In the Format Cells box, click the Number tab. In the Category list, click Date, and then choose a date format you want in Type.


4 Answers

( '0' + (myDate.getMonth()+1) ).slice( -2 );

Example: http://jsfiddle.net/qaF2r/1/

like image 196
user113716 Avatar answered Sep 29 '22 10:09

user113716


I don't like so much string concatenation:

var month = myDate.getMonth()+1,
    prettyData = [
        myDate.getDate(), 
        (month < 10 ? '0' +  month : month), 
        myDate.getFullYear()
    ].join('');
like image 24
Felix Kling Avatar answered Sep 29 '22 08:09

Felix Kling


You can use something like:

function addZ(n) {
  return (n < 10? '0' : '') + n;
}
like image 28
RobG Avatar answered Sep 29 '22 09:09

RobG


var myDate = new Date();
var newMonth = myDate.getMonth()+1;
var prettyDate =myDate.getDate() + '' + (newMonth < 9 ? "0"+newMonth:newMonth) + '' +         myDate.getFullYear();
$("#date").val(prettyDate);
like image 24
Griffin Avatar answered Sep 29 '22 09:09

Griffin