How to Add a Date Function in JavaScript
Interactive functionality makes a website more dynamic and provides greater interest for users. JavaScript is a client-side scripting language often used to insert Web page features such as form interaction and dynamic information display. JavaScript allows you to create functions that can be called within a page by using the function name. Create a JavaScript function to add a date to your Web page.
Instructions
-
-
1
Open your HTML document.
-
2
Type the function between the script tags:
<script>
function addDate(){
dateinfo = new Date();
document.write((dateinfo.getMonth() + 1) +"/"+dateinfo.getDate()+ "/"+ dateinfo.getYear());
}
</script>
The function uses the JavaScript built-in function Date() to create a date object. The date object is then used with the date methods, getMonth, getDate and getYear to get the current month, day and year respectively.
-
-
3
Type the function name within script tags where you want to display the date:
<p>The current date is <script>addDate()</script></p>
-
4
Save your document and view it in an Internet browser to test the script.
-
1
Resources
- Photo Credit Thinkstock Images/Comstock/Getty Images