Display Current Date and Time in Html using Javascript

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:

Читайте также:  Генератор арифметической прогрессии python

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;

Источник

Get Today’s Date in HTML

Get Today

  1. Use the JavaScript Date() Function to Get the Current Date in HTML
  2. Get the Current Date in the y/m/d Format in HTML
  3. Get the Current Date Using the JavaScript Method toLocaleDateString() in HTML

In this article, we will introduce a few methods to get the current date in HTML.

Use the JavaScript Date() Function to Get the Current Date in HTML

We can use the JavaScript Date() function to get the current date. The function returns the current date and time. We can create an HTML container and display the current date in it using JavaScript. We will use the innerHTML property to write the date in HTML.

For Example, create a div and set current_date as its id. Then, write some JavaScript inside the script tag. Select the current_id using the getElementById property and call the Date() function. Use the innerHTML property to write the returned date in HTML.

The example below will display the current date and time as shown in the output section below. The output contains the day of the week, month, day, year, hour, minute, second, and the GMT and the information about the location.

div id="current_date">p> script> document.getElementById("current_date").innerHTML = Date();  script> 

Get the Current Date in the y/m/d Format in HTML

We can also find the current date in y/m/d format using the various JavaScript Date() methods. We can get the current year from the getFullYear() method, the current month from the getMonth() method and the current day from the getDate() method. In this method, we will use the Date() object to access these various functions. We can format the date in any way we want and display it on an HTML page using the innerHTML property.

For example, create a div with the same id as in the method above. In JavaScript, create a date object of the Date() class. Next, create three variables year , month and day . Use the date object to call the methods getFullYear() , getMonth() and getDate() , and store in those respective variables. Next, use the document object and call the getElementById property to select the id of the div . Next, set the innerHTML to the variables month , day and year separated by a slash.

In this way, we can get the current date in m/d/y format in HTML using the JavaScript Date() class.

div id="current_date">p> script> date = new Date(); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); document.getElementById("current_date").innerHTML = month + "/" + day + "/" + year;  script> 

Get the Current Date Using the JavaScript Method toLocaleDateString() in HTML

We can use the JavaScript function toLocaleDateString() to find the current date. The toLocaleDateString() function returns the current date according to the language provided in the function. There are various language-specific conventions, and we can define the language with the toLocaleDateString() function. The function takes two parameters which are locales and options . We can specify the language of the output by the locales option. For example, we can use en-US for US English and en-GB for British English.

For example, create a div and write JavaScript inside the script tag. Creae a date object of the Date() class and call the method toLocaleDateString() . Next, use document.write() to display the date variable.

We can see the output in the m/d/y format. Thus, we can use the toLocaleDateString() method to find the current date in HTML.

div> script> date = new Date().toLocaleDateString(); document.write(date);  script>  div> 

Источник

JavaScript Date Now – How to Get the Current Date in JavaScript

Vijit Ail

Vijit Ail

JavaScript Date Now – How to Get the Current Date in JavaScript

Many applications you build will have some sort of a date component, whether it’s the creation date of a resource, or the timestamp of an activity.

Dealing with date and timestamp formatting can be exhausting. In this guide, you will learn how to get the current date in various formats in JavaScript.

JavaScript’s Date Object

JavaScript has a built-in Date object that stores the date and time and provides methods for handling them.

To create a new instance of the Date object, use the new keyword:

The Date object contains a Number that represents milliseconds passed since the Epoch, that is 1 January 1970.

You can pass a date string to the Date constructor to create an object for the specified date:

const date = new Date('Jul 12 2011');

To get the current year, use the getFullYear() instance method of the Date object. The getFullYear() method returns the year of the specified date in the Date constructor:

const currentYear = date.getFullYear(); console.log(currentYear); //2020

Similarly, there are methods for getting the current day of the month and the current month:

const today = date.getDate(); const currentMonth = date.getMonth() + 1; 

The getDate() method returns the current day of the month (1-31).

The getMonth() method returns the month of the specified date. One point to note about the getMonth() method is that it returns 0-indexed values (0-11) where 0 is for January and 11 for December. Hence the addition of 1 to normalize the month’s value.

Date now

now() is a static method of the Date object. It returns the value in milliseconds that represents the time elapsed since the Epoch. You can pass in the milliseconds returned from the now() method into the Date constructor to instantiate a new Date object:

const timeElapsed = Date.now(); const today = new Date(timeElapsed);

Formatting The Date

You can format the date into multiple formats (GMT, ISO, and so on) using the methods of the Date object.

The toDateString() method returns the date in a human readable format:

today.toDateString(); // "Sun Jun 14 2020"

The toISOString() method returns the date which follows the ISO 8601 Extended Format:

today.toISOString(); // "2020-06-13T18:30:00.000Z"

The toUTCString() method returns the date in UTC timezone format:

today.toUTCString(); // "Sat, 13 Jun 2020 18:30:00 GMT"

The toLocaleDateString() method returns the date in a locality-sensitive format:

today.toLocaleDateString(); // "6/14/2020"

You can find the complete reference for the Date methods in the MDN documentation.

Custom Date Formatter Function

Apart from the formats mentioned in the above section, your application might have a different format for data. It could be in yy/dd/mm or yyyy-dd-mm format, or something similar.

To tackle this problem, it would be better to create a reusable function so that it can be used across multiple projects.

So in this section, let’s create a utility function that will return the date in the format specified in the function argument:

const today = new Date(); function formatDate(date, format) < // >formatDate(today, 'mm/dd/yy');

You need to replace the strings «mm», «dd», «yy» with the respective month, day and year values from the format string passed in the argument.

To do that you can use the replace() method like shown below:

format.replace('mm', date.getMonth() + 1);

But this will lead to a lot of method chaining and make it difficult to maintain as you try to make the function more flexible:

format.replace('mm', date.getMonth() + 1) .replace('yy', date.getFullYear()) .replace('dd', date.getDate());

Instead of chaining methods, you can make use of regular expression with the replace() method.

First create an object that will represent a key-value pair of the substring and its respective value:

Next, use regular expression to match and replace the strings:

formattedDate = format.replace(/mm|dd|yy|yyy/gi, matched => map[matched]);

The complete function looks like this:

function formatDate(date, format) < const map = < mm: date.getMonth() + 1, dd: date.getDate(), yy: date.getFullYear().toString().slice(-2), yyyy: date.getFullYear() >return format.replace(/mm|dd|yy|yyy/gi, matched => map[matched]) >

You can also add the ability to format timestamps in the function.

Conclusion

I hope you now have a better understanding of the Date object in JavaScript. You can also use other third-party libraries like datesj and moment to handle dates in your application.

Until next time, stay safe and keep hustling.

Vijit Ail

Vijit Ail

I’m a Full Stack Developer based in Mumbai who loves to build modern and performant applications. https://vijitail.dev/

If this article was helpful, tweet it .

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

Оцените статью