How to write a date dynamically with HTML and JavaScript

How to write a date dynamically with HTML and JavaScript

This article covers how you can automatically update the dates in your website.

ยท

2 min read

Table of contents

The day is January 1, everyone is celebrating the new year, champagnes are popping and hugs are been shared. Unexpectedly, your boss or client calls you, and asks, 'Why is the old year still reflecting on the/my website?'

Embarrassing? ๐Ÿ˜’๐Ÿ˜’

Well, the content of this article prevents that from ever happening!

The JavaScript Date object is represented in milliseconds in a string format. It returns the value of the number of milliseconds that have passed since January 1, 1970, UTC.

Generally, it is called as a constructor: new Date(). Similarly, it can also be called as a function with no arguments: Date(). The code returns the local time zone of the host system.

console.log(new Date())
console.log(Date())

// It returns the same value = Sat Dec 17 2022 12:12:25 GMT+0100 (West Africa Standard Time) (The value returned is the current time on my local system)

There are different methods that can be called on the Date object to get a particular result.

//To get the full year
new Date().getFullYear()
//To get the date of the month
new Date().getDate()
//To get the day of the week. (It starts with an index of 0 returns the day of the week in number format from 0-6. e.g, 0 = Sunday, 3 = Wednesday etc.)
new Date().getDay()
//To get hours 
new Date().getHours()

To get the full methods, you can read the docs: Dates

To configure your HMTL code date dynamically with JavaScript, follow these steps:

In the HTML file:

<p>The year is <span class='date'><span></p>

In the JavaScript file:

//Save the id in the HTML file in a constant variable
const date = getElementById('date')
date.textContent = new Date().getFullYear()

//The year will be automatically updated. You could also use any method.

References

Official Docs on Dates in JavaScript

ย