javascript getDate issue
I was won开发者_Go百科dering if anyone could help me get the leading zero to show up when I do a getDate? Right now it's showing up as 8/3/2010 ... I would like it 08/03/2010.
You need to detect if the value of the day and month is less than 10 and add the zero yourself:
var today = new Date();
var day = today.getDate();
var month = today.getMonth() + 1;
var year = today.getFullYear();
var formatted =
(day < 10 ? "0" : "") + day + "/" +
(month < 10 ? "0" : "") + month + "/" +
year;
alert(formatted);
You can see it in action here. Note that you add one to the month as January = 0 rather than 1.
I coded an example for you:
<script type="text/javascript">
<!--
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
curr_month = curr_month + "";
if(curr_month.length == 1){
curr_month = "0" + curr_month;
}
curr_date = curr_date + "";
if(curr_date.length == 1){
curr_date = "0" + curr_date;
}
document.write(curr_month + "/" + curr_date + "/" + curr_year);
-->
</script>
here is a nice blogpost on how to implement a dateformat function
if you are using mootools you cat use the Native/Date function
for jquery there is a dateformat plugin
You need to either DIY or find a script.
The link provided by haim evgi is sufficient. After including the library, you can use it as followed:
var d = new Date;
alert(d.format('d/m/Y'));
Use this lib: http://blog.stevenlevithan.com/archives/date-time-format Solved formatting issues for me on many levels ;)
精彩评论