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.
Prerequisites
- Basic understanding of JavaScript
- JavaScript's Built-in Date.getTime() Method
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.
Related Content
- Learn more about JavaScript
- Learn more about JavaScript Arrays
- JavaScript Program to Add Two Numbers
- JavaScript Program to Calculate the Area of a Triangle
- JavaScript Program to Convert Date to a Number
- JavaScript Program to Find the Square Root of a Number
- JavaScript Program to Pass a Function as a Parameter
- JavaScript Program to Remove all Whitespaces From a Text
- JavaScript Program to Write Console Statements
- JavaScript Hello World Program
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.