javascript 将 0 添加到 jQuery 日期中的月份
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7019578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding 0 to months in jQuery date
提问by Callum Whyte
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).
我有一个 jQuery 脚本,它将当前日期返回到一个文本框中。但是,当显示只有一位数字的月份(例如 8)时,我希望它在它之前放置一个 0(例如 08),如果它有 2 个数字(例如 11),则不要在它之前放置一个 0。
How can I do this? I hope you can understand my question. Here is my jQuery code:
我怎样才能做到这一点?我希望你能理解我的问题。这是我的 jQuery 代码:
var myDate = new Date();
var prettyDate =myDate.getDate() + '' + (myDate.getMonth()+1) + '' + myDate.getFullYear();
$("#date").val(prettyDate);
回答by user113716
( '0' + (myDate.getMonth()+1) ).slice( -2 );
Example:http://jsfiddle.net/qaF2r/1/
回答by Felix Kling
I don't like so much string concatenation:
我不喜欢这么多的字符串连接:
var month = myDate.getMonth()+1,
prettyData = [
myDate.getDate(),
(month < 10 ? '0' + month : month),
myDate.getFullYear()
].join('');
回答by RobG
You can use something like:
你可以使用类似的东西:
function addZ(n) {
return (n < 10? '0' : '') + n;
}
回答by BNL
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/
有许多 JS 库可以提供良好的字符串格式。这个是c#风格的。http://www.masterdata.dyndns.org/r/string_format_for_javascript/
回答by Joseph Marikle
(myDate.getMonth() + 1).toString().replace(/(^.$)/,"0")
I love regex :)
我喜欢正则表达式 :)
回答by Griffin
var myDate = new Date();
var newMonth = myDate.getMonth()+1;
var prettyDate =myDate.getDate() + '' + (newMonth < 9 ? "0"+newMonth:newMonth) + '' + myDate.getFullYear();
$("#date").val(prettyDate);