Displaying Date with format

By using JavaScript date object we will collect the date of the month. Date of the month is starting from 1 to 31 ( based on the current month ) . The simple function getDate() will return the number of the date of the month.

var dt= new Date();
var my_date= dt.getDate();
The output is a number based on the todays date.

Formatting the date

We will try to format this date returned by the above getDate() method. Our formatting will depend on the last digit of the month returned by the above getDate function. If the last digit is 1 then we will add 'st' to the end like 21st , it is “nd” for 2, “rd” for 3, “th” for 4 and other digits. To get this format we will use if and if, else condition to know what should be used based on the last digit. We will get the last digit of the day returned by dividing it with 10 and taking the quotient. This way from 21 we will get 1 and from 17 we will get 7. Here is the code to get the last digit from any number.
var last_digit= my_date % 10;
Here my_date variable stores the date returned by getDate function. We will add the ending format to the date value and display the value in an alert box.



Here is the full code of the above demo.


<html>

<head>
<title>(Type a title for your page here)</title>
<script type="text/javascript"> 
function display() { 
var dt= new Date();
var my_date= dt.getDate();
/// Let us identify the format to display the date ////
// we have to add st if it is 1, nd to be added for 2 and rd for 3 and th for other

// let is find out the last digit of the date number
var last_digit= my_date % 10;
var format;
if(last_digit==1) 
format="st";
else 
if(last_digit==2)
format="nd";
else
if(last_digit==3 && my_date !=13)
format="rd";
else
format="th";
my_date=my_date + format;
//////// End of identifying date format ///////
alert(my_date); 
}
</script>
</head>

<body>
<input type=button name=test value='Show Date' onclick="display();">

</body>
</html>

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com




    Post your comments , suggestion , error , requirements etc here .




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer