Display Current Date and Time in Html using Javascript

HOW TO — Display current date and time in HTML

In this post, I will go over how to display the current date and time in HTML.

With some web design clients, I found that this is a common requirement that is asked.

Usually this can be from ecommerce clients wanting a countdown timer or just want to show the current local time.

To do this we need to create a HTML, CSS and the magic in Javascript!

Prerequisites

Generally, to follow along, you will need basic understand of HTML and CSS.

The JavaScript is not that difficult and I will go through it step by step!

Setting up the HTML

Here, you can describe and provide an example of the basic HTML structure needed for displaying the date and time.

  • styles.css — this is where we will apply our style to make it look pretty!
  • script.js — this is Javascript code to update the time
  • index.html — the main HTML file
. └── my-app/ ├── styles.css ├── script.js └── index.html

Styling the timer with CSS

Display live time with Javascript

  So the script can look a bit daunting, but it really does a simple thing. It will update the text in our HTML above:

This will be updated every second (eg 1000 milliseconds).

window.onload = function() <. >— Generally, this is event that will be run when everything is loaded in your page (scripts, CSS, images). This makes the code to be more reliable because the browser will load some things asynchronously (eg CSS or images) and others synchronously. We just want to make sure that our script is consistent every time!

setInterval(function()<. >, 1000) This is the main function that will trigger every second. It just tells the browser to run do the below instructions every “interval”. In this case, the interval is 1000 milliseconds, or 1 second.

Inside the function that is set to repeat every second:

var displayDate = date.toLocaleDateString(); — the toLocaleDateString() method to convert the date portion of the Date object into a string using the current locale’s settings.

var displayTime = date.toLocaleTimeString(); — the toLocaleTimeString() method is used to convert the time portion of the Date object into a string using the current locale’s settings.

Understanding locales

We are using the two functions toLocaleDateString, and toLocaleDateString because we want to display the time in the user’s browser/system settings.

We need to do this because display dates and times is displayed differently for different countries.

For example, in the United States, dates are typically formatted as “month/day/year”, and times are formatted in a 12-hour format with AM or PM (like “2:30 PM”).

However with many European countries, dates are typically formatted as “day.month.year”, and times are often in 24-hour format (like “14:30”).

So if a user in the United States views a date and time formatted with toLocaleDateString() and toLocaleTimeString(), they might see “12/31/2023, 2:30 PM”, while a user in Germany viewing the same code could see “31.12.2023, 14:30”.

How to display current time in HTML textbox

Another use case is when we want to display the time in a HTML textbox.

For example if someone does to your booking website, we want to display the current date/ time to help them not manually entering it in.

The HTML code might look something like this:

In our script.js code, we have the following:

   Now we can see that this example is a bit different, since it uses the requestAnimationFrame function instead of the setInterval function.

Generally, in this case it might not be needed, I like to introduce it since its another alternative way.

The requestAnimationFrame just runs before the next repaint of the browser, which can be up to 60 times per second in most modern browsers.

So this is a good choice for animations and other visual updates like updating a clock display. You might consider this if you are using heavy animations.

The advantage of requestAnimationFrame over setInterval is that it’s synced with the browser’s refresh rate, and it will not run if the tab is not active, which can save system resources.

Additionally, requestAnimationFrame is GPU bound and setInterval is CPU bound. So any complex Javascript calculations will be make setInterval animations janky.

If animations are done with requestAnimationFrame , it can look smoother!

It’s important to note that the update rate could be higher than once per second since requestAnimationFrame aims to run at the screen refresh rate (usually 60 times per second).

Now for our clock app, this isn’t a big issue, but for more resource-intensive updates, you might need to limit the update frequency.

Summary

In this post, we went over how to display the current date and time using HTML.

Generally we will need 3 files, one is the HTML file, next is the CSS and the final piece is the JavaScript to update the time every second!

The idea is to have Javascript function that runs every 1 second (using setInterval ) and update the HTML text.

When we are updating the date and time, we need to consider locales and use the toLocaleDateString and toLocaleTimeString functions to display the date and time in the user’s locale settings.

Finally as a more advanced option, we considered using the requestAnimationFrame over the setInterval .

This function is more advanced and suitable for scenarios where you want to have lots of interactions.

👋 About the Author

G’day! I am Kentaro a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.

My aim to share what I have learnt with you! (and to help me remember 😅)

👉 See Also 👈

Источник

Display Current Date and Time in HTML using JavaScript

In this tutorial, you will learn how to display current system date and time in HTML using JavaScript.

Will take an example to display current Date and Time in H2 html tag with using javascript document.getElementById(“ID”).innerHTML. As well as display current day name.

JavaScript Code to Display Current System Date and Time

JavaScript Code

var today = new Date(); var day = today.getDay(); var daylist = ["Sunday","Monday","Tuesday","Wednesday ","Thursday","Friday","Saturday"]; var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate(); var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds(); var dateTime = date+' '+time; document.getElementById("displayDateTime").innerHTML = dateTime + ' 
Day :- ' + daylist[day];

HTML Source Code with JavaScript

    

Get current date using JavaScript.

var today = new Date(); var day = today.getDay(); var daylist = ["Sunday","Monday","Tuesday","Wednesday ","Thursday","Friday","Saturday"]; var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate(); var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds(); var dateTime = date+' '+time; document.getElementById("displayDateTime").innerHTML = dateTime + '
Day :- ' + daylist[day];

You can learn more about the JavaScript date and time methods:

Get Current Date & Time in JavaScript

Use Date() method to create an object in JavaScript with current date and time. This provides output in UTC timezone.

1. Current Date in JavaScript

Use the following script to get the current date using JavaScript in “Y-m-d” format.

var today = new Date(); var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
  • getFullYear() – Provides current year like 2020.
  • getMonth() – Provides current month values 0-11. Where 0 for Jan and 11 for Dec. So added +1 to get result.
  • getDate() – Provides day of the month values 1-31.

2. Current Time in JavaScript

Use the following script to get the current time using JavaScript in “H:i:s” format.

var today = new Date(); var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
  • getHours() – Provides current hour between 0-23.
  • getMinutes() – Provides current minutes between 0-59.
  • getSeconds() – Provides current seconds between 0-59.

3. Current Date & Time Both in JavaScript

Use the following script to get the current date and time using JavaScript in “Y-m-d H:i:s” format. You can simply combine the output of the above JavaScript code in one variable as below:

var today = new Date(); var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate(); var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds(); var dateTime = date+' '+time;

Источник

: The (Date) Time element

The HTML element represents a specific period in time. It may include the datetime attribute to translate dates into machine-readable format, allowing for better search engine results or custom features such as reminders.

It may represent one of the following:

  • A time on a 24-hour clock.
  • A precise date in the Gregorian calendar (with optional time and timezone information).
  • A valid time duration.

Try it

Attributes

Like all other HTML elements, this element supports the global attributes.

This attribute indicates the time and/or date of the element and must be in one of the formats described below.

Usage notes

This element is for presenting dates and times in a machine-readable format. For example, this can help a user agent offer to add an event to a user’s calendar.

This element should not be used for dates prior to the introduction of the Gregorian calendar (due to complications in calculating those dates).

The datetime value (the machine-readable value of the datetime) is the value of the element’s datetime attribute, which must be in the proper format (see below). If the element does not have a datetime attribute, it must not have any element descendants, and the datetime value is the element’s child text content.

Valid datetime values

a valid yearless date string

a valid local date and time string

a valid global date and time string

Источник

Читайте также:  Css шаблон с формами
Оцените статью