Question – How do I get the current date and time in JavaScript? How to get the date in Y-m-d format in JavaScript? How do I get time in H:i:s format in JavaScript?

Advertisement

Time is an important part of our life and we cannot avoid it. In our daily routine, we need to know the current date or time frequently. JavaScript provides a global variable Date which helps you to get the current Date & Time in JavaScript. However, it won’t give you accurate information and rather return the local computer time instead of UTC time. To get accurate Date & Time in JavaScript, you need to use different APIs provided by JavaScript itself. You can also get the date and time in your formats like YYYY-MM-DD and HH:MM:SS formats.

This article explains all about getting the current Date & Time in JavaScript with examples and best practices.

Get Current Date & Time in JavaScript

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

1. Current Date in JavaScript

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

  • getFullYear() – Provides current year like 2022.
  • getMonth() – Provides current month values 0-11. Where 0 for Jan and 11 for Dec. So added +1 to get the 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.

  • 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 the “Y-m-d H:i:s” format. You can simply combine the output of the above JavaScript code in one variable as below:

Output
2022-8-4 11:0:38
Share.

31 Comments

  1. ok but how can i get this dynamicl i mean to change this value on the website second by seconds.. need i use a API? 🙁

    • Muhammad Bilal Mohib-ul-Nabi on

      Works well and update on page refresh or if you have used a button to display it like
      Time

      function showTime()
      {
      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;
      var show=document.getElementById(“show”);
      show.innerHTML=input;
      }

      //Now if you will click the button time will update

  2. var date = new Date().toJSON().slice(0,10);
    var time = new Date().toJSON().slice(11,19)
    var dateTime = date+’ ‘+time;

  3. This way when the minute is < 10 it will be displayed as e.g. '10:03' and not '10:3'
    if(today.getMinutes() < 10){
    var time = today.getHours() + ':0' + today.getMinutes();
    }
    enjoy..

Leave A Reply