Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Oct 2009
    Posts
    434
    Thanks
    7
    Thanked 3 Times in 3 Posts

    how to return date with leading zero's

    I have the following which returns the date in the format I need it in but it does not have the leading zero's

    Code:
    var wholeDate = getTheDay();
    
    function getTheDay(){
    
    	var d = new Date();
    	var year = d.getFullYear();
    	var numMonth = d.getMonth() + 1;
    	var day = d.getDate();
    	var whole = year + '-' + numMonth + '-' + day;
    	alert(whole);
    	return whole;
    
    }
    Would return todays date as 2012-1-5

    How do I get the date returned like

    2012-01-05 ?

  • #2
    Regular Coder
    Join Date
    Jan 2004
    Location
    USA
    Posts
    364
    Thanks
    12
    Thanked 6 Times in 6 Posts
    How about this?

    Code:
    var wholeDate = getTheDay();
    
    function getTheDay(){
    
    	var d = new Date();
    	var year = d.getFullYear();
    	var numMonth = (d.getMonth() > 8 ? "" : "0") + (d.getMonth() + 1);
    	var day = (d.getDate() > 9 ? "" : "0") + d.getDate();
    	var whole = year + '-' + numMonth + '-' + day;
    	alert(whole);
    	return whole;
    
    }
    Running Windows 7 x64

  • Users who have thanked qwertyuiop for this post:

    needsomehelp (01-05-2012)

  • #3
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    This example uses the declared variable in the expression that determines its own value:
    Code:
    <script type='text/javascript'>
    
    function getTheDay()
    {
    	var d = new Date();
    	var year = d.getFullYear();
    	var numMonth = ( numMonth = d.getMonth() + 1 ) < 10 ? "0" + numMonth : numMonth;
    	var day = ( day = d.getDate() ) < 10 ? "0" + day : day;
    
    	return year + '-' + numMonth + '-' + day;
    }
    
    
    alert( getTheDay() );
    
    </script>


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •