How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Formatting a date in javascript
我知道javascript日期对象中的其他可能格式,但我没有了解如何将日期格式化为
如果你遇到这样的问题,请告诉我。
试试这个
1 2 3 4 5 6 7 | var d = new Date, dformat = [d.getMonth()+1, d.getDate(), d.getFullYear()].join('/')+' '+ [d.getHours(), d.getMinutes(), d.getSeconds()].join(':'); |
如果希望值小于10的前导零,请使用此数字扩展名
1 2 3 4 5 6 7 | Number.prototype.padLeft = function(base,chr){ var len = (String(base || 10).length - String(this).length)+1; return len > 0? new Array(len).join(chr || '0')+this : this; } // usage //=> 3..padLeft() => '03' //=> 3..padLeft(100,'-') => '--3' |
应用于上一个代码:
1 2 3 4 5 6 7 8 | var d = new Date, dformat = [(d.getMonth()+1).padLeft(), d.getDate().padLeft(), d.getFullYear()].join('/') +' ' + [d.getHours().padLeft(), d.getMinutes().padLeft(), d.getSeconds().padLeft()].join(':'); //=> dformat => '05/17/2012 10:52:21' |
在jsFiddle中查看此代码
也见
1 2 3 4 5 6 7 8 9 | var d = new Date(); alert( ("00" + (d.getMonth() + 1)).slice(-2) +"/" + ("00" + d.getDate()).slice(-2) +"/" + d.getFullYear() +"" + ("00" + d.getHours()).slice(-2) +":" + ("00" + d.getMinutes()).slice(-2) +":" + ("00" + d.getSeconds()).slice(-2) ); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | var d = new Date(); // calling the function formatDate(d,4); function formatDate(dateObj,format) { var monthNames = ["January","February","March","April","May","June","July","August","September","October","November","December" ]; var curr_date = dateObj.getDate(); var curr_month = dateObj.getMonth(); curr_month = curr_month + 1; var curr_year = dateObj.getFullYear(); var curr_min = dateObj.getMinutes(); var curr_hr= dateObj.getHours(); var curr_sc= dateObj.getSeconds(); if(curr_month.toString().length == 1) curr_month = '0' + curr_month; if(curr_date.toString().length == 1) curr_date = '0' + curr_date; if(curr_hr.toString().length == 1) curr_hr = '0' + curr_hr; if(curr_min.toString().length == 1) curr_min = '0' + curr_min; if(format ==1)//dd-mm-yyyy { return curr_date +"-"+curr_month+"-"+curr_year; } else if(format ==2)//yyyy-mm-dd { return curr_year +"-"+curr_month+"-"+curr_date; } else if(format ==3)//dd/mm/yyyy { return curr_date +"/"+curr_month+"/"+curr_year; } else if(format ==4)// MM/dd/yyyy HH:mm:ss { return curr_month+"/"+curr_date +"/"+curr_year+""+curr_hr+":"+curr_min+":"+curr_sc; } } |
1 2 3 4 5 6 7 8 9 | var d = new Date(); var curr_date = d.getDate(); var curr_month = d.getMonth(); var curr_year = d.getFullYear(); document.write(curr_date +"-" + curr_month +"-" + curr_year); |
使用这个可以格式化日期。
你可以按照你想要的方式改变外观。
有关更多信息,请访问此处