SQL PHP HTML ASP JavaScript articles and free scripts to download
JavaScript Tutorials
Popular Tutorials
Drop down list
Timer function
JavaScript Tutorials
String
Array
Date & Time
Form Validation
Event Handling
Math Functions
JavaScript Forum
Subscribe
Submit your email address and receive article and product notifications. Your email is safe with us.

 
 

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();

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)
format="rd";
else
format="th";
my_date=my_date + format;
//////// End of identifying date format ///////
alert(my_date);
}
</script>
</head>

<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000">

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

</body>

</html>
Further readings
Countdown script displaying days , hours , minutes and seconds left from an event
Displaying changing Clock showing date and time in a web page
Timer function to set time for reminder alert
Timer Resetting the timer function
Displaying current date and time alert
Displaying Current Month using getMonth() function
Displaying present Year using getFullYear()
Showing Current Date using getDate() function
Displaying Current Day using getDay() function
 
Subscribe
Submit your email address and receive article and product notifications. Your email is safe with us.

Scripts
PHP
JavaScript