开发者

Adding 0 to months in jQuery date

I have a jQuery script which ret开发者_如何学运维urns 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);


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


There are a number of JS libraries that provide good string formatting. This one does it c# style. http://www.masterdata.dyndns.org/r/string_format_for_javascript/


(myDate.getMonth() + 1).toString().replace(/(^.$)/,"0$1")

I love regex :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜