How To Get Current Date & Time In JavaScript?

Someone please help me with the code to fetch the current date and time in JavaScript.

1 Like

Creating the Date Object in JavaScript The JavaScript Date object helps when working with dates. To create a new object the with current date and time, add the Date variable to your script:

<script>

var today = new Date();

</script>

Use the Get Method to Show the current Date in JavaScript

If you want to get the date in the YYYY-MM-DD format, edit the date_test.html document, and add the following variable:

<script>

var today = new Date();

var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();

</script>

The second line consist of the following instructions:

today.getFullYear() – Uses the today variable to display the 4-digit year.

today.getMonth()+1 – Displays the numerical month – the +1 converts the month from digital (0-11) to normal.

today.getDate() – Displays the numerical day of the month.

Note: If you prefer a different format, simply change the order of the commands.

Display Hours, Minutes, and Seconds using JavaScript

To show the time in HH:MM:SS format, edit your script to look as follows:

<script>

var today = new Date();

var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();

</script>

today.getHours() – This uses the today variable to display the current hour. This uses a 24-hour clock.

today.getMinutes() – Displays the current minute reading.

today.getSeconds() – Displays the current seconds reading.

Show the Full Current Date and Time in JavaScript

Combine the two commands to show full date and time in the YYYY-MM-DD and HH:MM:SS formats. Edit your script as follows:

<script>

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;

</script>

The final line combines the two other pieces of code. This instructs the system to display the full date next to the full time.

1 Like