JavaScript Program to Convert Date to Number

JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.

JavaScript Program to Convert Date to Number

Prerequisites

Convert Date to Number in JavaScript

We will be using the Date.getTime() method to convert a date to a number.

In the example below, the new Date() constructor is used to create a date object. It returns the current date and time. The getTime() method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.


// function to convert date to number
function convertDateToNumber(currentDate) {
  // date.getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 UTC
  var dateNumber = date.getTime();
  return dateNumber;
}

// store the current date in a variable
const currentDate = new Date();
console.log(currentDate); // Fri Jul 22 2022 15:09:41 GMT-0600 (Mountain Daylight Time)

// pass the current date as an argument to the function convertDateToNumber
console.log(convertDateToNumber(date)); // 1658524181766

Summary

In this tutorial, we have learnt how to convert a date to a number using the JavaScript's built-in Date.getTime() method. We also looked into the Date() constructor to create a date object.

Please checkout our related content section below for more tutorials on similar topics.


We hope that you have learnt something from our tutorials. Please feel free to share this content with your friends.


If you have any questions or want some other content to be added to our website so that it can help you learn and grow further, please do not hesitate to contact us at info@createmysite.org. We would love to hear from you.

We are hiring!! If you are tech blogger who loves writing content on modern technologies, we would love to get in touch with you. Just drop us a mail at the email address mentioned above and we will reach out to you as soon as possible.

If you are interested in learning more about our website, please visit our about page.