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);
var MyDate = new Date(); var MyDateString; MyDate. setDate(MyDate. getDate() + 20); MyDateString = ('0' + MyDate. getDate()).
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.
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.
( '0' + (myDate.getMonth()+1) ).slice( -2 );
Example: http://jsfiddle.net/qaF2r/1/
I don't like so much string concatenation:
var month = myDate.getMonth()+1,
prettyData = [
myDate.getDate(),
(month < 10 ? '0' + month : month),
myDate.getFullYear()
].join('');
You can use something like:
function addZ(n) {
return (n < 10? '0' : '') + n;
}
var myDate = new Date();
var newMonth = myDate.getMonth()+1;
var prettyDate =myDate.getDate() + '' + (newMonth < 9 ? "0"+newMonth:newMonth) + '' + myDate.getFullYear();
$("#date").val(prettyDate);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With