How To Convert A Date Object To Ticks Using JavaScript?

Convert a Date object to Ticks using JavaScript

In this article, you’ll learn how to convert a Date object to Ticks using JavaScript by using Math. Let’s go into detail now.

Convert a Date object to Ticks using JavaScript

A side note before we started: In simple terms, a tick is a value that represents how many times an event queue has been passed. A more descript explanation of an event queue is here.

Although more important to know for this article, the Date class represents the number of milliseconds that have passed since ECMAScript’s epox (which is January 1st, 1970 or 1970-01-01 00:00:00:00 UTC+00) in your computer’s set timezone.

Explanation

Usually, with these kinds of problems, a function or a collection of functions would do them. However, no function or set of functions can convert a Date into ticks. The reason is not because the problem is complex but the solution is too simple to have any functionality. Or, to be specific, no function that would directly do that.

We need to use Math. Specifically multiplying the Date in milliseconds by 10000 and adding the Date class’ epox in ticks (which in this case is 621355968000000000). 

Solution

To get the Date in milliseconds, you need to use the Date class’ .getTime() or .valueOf() function (which are functionally interchangeable in most cases).

For example:

// Initialize date
const date = new Date(12, 9, 2022);

// Create the function to convert the date object to ticks
function DateToTicks(date) {
	const epox = 621355968000000000;
	const milliseconds = date.getTime();
	return milliseconds * 10000 + epox;
}

console.log(DateToTicks(new Date()));

Output:

638037781683430000

However, one thing to note is how the conversions are displayed, as in whether or not it is displayed in scientific notation.

If you decide to display the number in scientific notation, you can use the Number class’ .toExponential() function.

For example:

// Initialize date
const date = new Date(12, 9, 2022);

// Create the function to convert the date object to ticks
function DateToTicks(date) {
	const epox = 621355968000000000;
	const milliseconds = date.getTime();
	return milliseconds * 10000 + epox;
}

console.log(DateToTicks(new Date()).toExponential());

Output:

6.3803779873809e+17

Summary

To convert a Date object to Ticks using JavaScript, you need to convert the Date into milliseconds using the .valueOf() or .getTime() function, then multiply it by 10000 and add 621355968000000000. Let’s try this method. Good lucks to you!

Maybe you are interested:

Leave a Reply

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