Getting the current date and time javascript

When developing web applications, it is necessary to include the current date and time on which a particular operation was performed according to the user’s local zone. This requirement can be filled out using the date class. For instance, when you submit data via a form, you may want to include the date that the data was created or when the data was submitted.

JavaScript is a lightweight programming language used by the world wide web. The date prototype object in JavaScript is used to check the date and time a visitor arrives at your website. This article has been tailored to teach you how to quickly get the current date and time in JavaScript from scratch and use an external library such as the JavaScript date library.

Note that using an external library for such an operation is not recommended. If you already have a library installed on your machine or use it for other operations in your application, you are safe to use it. You can use various methods to get individual date and time elements. Below are some methods that will enable you to get the current date and time using JavaScript.

In JavaScript, you can quickly get the current date or time by using the new Date() object. By default, it will use the browser’s time zone and display the date and time as a full-text string, for example, “2022-10-22T05:42:15.392Z “. The JavaScript code below shows how to get the date and time as a full-text string.

const date = new Date();
console.log(date);
2022-10-22T05:42:15.392Z 

Getting the current date and time in JavaScript

The date class contains various methods. This means we can fetch the current date, day, and time. There are different methods that programmers use according to their requirements. Let us see how we can extract only the date from the long string above. Below is a discussion of the various methods you can use to extract the date string alone. 

1. Using the get method to show the current date in JavaScript

In case you want to get the date in the format YYYY-MM-DD, compile the code below:

const date = new Date();
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
let currentDate = `${day}-${month}-${year}`;
console.log(currentDate); 
22-10-2022

The code compiled above consists of the following instructions:

  • Date.get date () – This instruction displays the numerical day of the month (1-31).
  • Date.getMonth()+1 – This instruction displays the numeric month. It is a 0- based indexing; hence we add one to convert the month from digital (0-11) to normal—for example, 1 for January.
  • Date.getFullYear() – This instruction uses the today variable to display the year as a four-digit number(YYYY), for example, 2022.

Given that you prefer a different format other than this one, you will have to change the order of commands. For instance, you can decide to start with the year, month, and then the date. The code for such a format is shown below:

const date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
let currentDate = `${day}-${month}-${year}`;
console.log(currentDate);
2022-10-22

It is important to put a dash between each command so that the date class can be easily noticeable. This dash will create a dash between the segment of each date class. You can also replace the dash with whatever you prefer, for example, a full stop or a forward slash for example:

const date = new Date();
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
let currentDate = `${day}.${month}.${year}`;
console.log(currentDate);
22.10.2022

2. Using the toJSON() method to get the current date

The toJSON() method always returns the date in the format yyyy-mm-dd. In addition to the date object, the time object is also included in the format hh: mm: ss: ms. An example of a code compiled using this method is shown below:

let date = new Date().toJSON();
console.log(date); 
2022-10-22T02:51:01.660Z

If you are only interested in the date class and not the time class, you should use the slice() method to get the date class. Since the date class has ten characters, you will slice the whole string from 0 to 10, as shown below:

let date = new Date().toJSON().slice(0,10);
console.log(date); 
2022-10-22

3. How to use the toLocaleDateString() to get the date class

This is one of the simplest methods that returns the date object as a string by using local convections. For instance, the date format between various languages differs, but this method accepts an argument to correct that. This method takes in two parameters. One parameter is the locale, and the other one is the options.

Locale refers to the local zone or region whose data you want to take. It represents the Unicode for the local region. For example, if you’re going to get the current date and time of India, you should pass ‘en-IN’ and ‘en-US’ for the US users. The options parameter is the object that contains many properties, such as the formatting of date and time. To find out how this method works, first pass an argument as shown in the code below:

let date = new Date().toLocaleDateString();
console.log(date)
10/22/2022

Suppose you are interested in the time in Germany; enter the locale code of Germany, and you will be good to go.

let date = new Date().toLocaleDateString("de-DE");
console.log(date)
22.10.2022

When using this method, one should be familiarized with the locale codes.

4. How to use the get method to show the current time

If you want to get the time in HH: MM: SS format, edit your script to the format below.

const date = new Date();
let hours = date.getHours();
let minutes= date.getMinutes();
let seconds = date.getSeconds();
let currentDate = `${hours}:${minutes}:${seconds}`;
console.log(currentDate);
7:8:27

The code above consists of the following instructions.

  • Date.getHours() – by the help of today’s variable, this instruction displays the current hour in a 24-hour clock
  • Date.getMinutes() – this instruction displays the current minute reading.
  • Date.getSeconds() – it displays the current recording of the seconds.

There is a colon between each command. Its purpose is to separate numeric display, showing the time like a clock.

5. How to get the full current date and time

To get the full date and time in the YYYY – MM -DD and HH: MM: SS formats, you must edit your code as follows.

    var date = new Date();
	var current_date = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+ date.getDate();
	var current_time = date.getHours()+":"+date.getMinutes()+":"+ date.getSeconds();
	var date_time = current_date+" "+current_time;
	console.log(date_time);
    2022-10-22 7:43:19

The final line,console.log(date_time), combines the two other pieces of code, instructing the system to display the full date next to the full time.


6. How to use Moment.js to get the current date and time

Moment.js is among the most popular date packages that are available to everyone. It can be used to get the current date. If you have it installed in your project, all you need to do is to get the current date as follows:

var date = moment();
var currentDate = date.format('D/MM/YYYY');
console.log(currentDate); 
22/10/2022

You can also manipulate it based on how you want the date’s format to appear.

Conclusion

After reading through this article, you should be able to write a simple JavaScript code to retrieve the current date and time in a practical, profound, and effective way that any beginner can understand and use. The snippets above can also help create a timestamp by linking this script with an action and writing it into a log file. It would be best if you kept learning, working, and getting experience to grasp it better.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *