JavaScript Date getTime() Method



In JavaScript, the Date.getTime() method will return a numeric value that represents the number of milliseconds between the date object and Epoch. The Epoch is the starting point for measuring time in seconds and is defined as January 1, 1970, 00:00:00 UTC.

This method will return Not a Number (NaN), when the Date object provided is invalid. The return value will always be a non-negative integer.

This method is functionally equivalent to the valueOf() method.

Syntax

Following is the syntax of JavaScript Date getTime() method −

getTime();

This method does not accept any parameters.

Return Value

This method returns a numeric value representing the number of milliseconds between the specified date and time and the Unix epoch.

Example 1

In the following example, we are demonstrating the usage of JavaScript Date getTime() method −

<html>
<body>
<script>
   const currentDate = new Date();
   const timestamp = currentDate.getTime();

   document.write(timestamp);
</script>
</body>
</html>

Output

The above program returns the number of milliseconds since epoch.

Example 2

In the below example, we provided a specific date and time (2023-12-26 06:30:00) to the date object −

<html>
<body>
<script>
   const currentDate = new Date('2023-12-26 06:30:00');
   const timestamp = currentDate.getTime();

   document.write(timestamp);
</script>
</body>
</html>

Output

It returns "1703574000000" milliseconds as output.

Example 3

In the example below, the date object is created with an invalid date i.e. the date and time values that are outside the valid range.

<html>
<body>
<script>
   const specificDate = new Date('2023-15-56 06:30:00');
   const dateString = specificDate.getTime();

   document.write(dateString);
</script>
</body>
</html>

Output

The program returns "NaN" as a result.

Advertisements