Borislav Hadzhiev
Thu Jan 20 2022·2 min read
Photo by Yoann Boyer
To convert a date object to ticks:
getTime()
method on the date to get the number of milliseconds
since the Unix Epoch.function dateToTicks(date) { const epochOffset = 621355968000000000; const ticksPerMillisecond = 10000; const ticks = date.getTime() * ticksPerMillisecond + epochOffset; return ticks; } console.log(dateToTicks(new Date())); console.log(dateToTicks(new Date('2022-01-20')));
We created a reusable function, which takes a Date
object as a parameter and
converts it to universal ticks.
A single tick represents one hundred nanoseconds.
getTime()
method on the Date
object instead.const millisecondsSinceEpoch = new Date('2022-01-20').getTime(); console.log(millisecondsSinceEpoch); // 👉️ 16426368000000
In our function, we stored the epoch offset in a variable. This is the number of nanoseconds between the 1st of January 0001 and the 1st of January 1970.
The second variable ticksPerMillisecond
stores the number of .net ticks there
are in a millisecond (10,000).
The getTime()
method returns the number of milliseconds since the Unix epoch,
so multiplying the value by the number of ticks in 1
millisecond (10,000)
gives us the number of ticks since Jan 1, 1970 00:00:00 UTC.
Adding the epoch offset to the result gives us the total number of ticks since the 1st of January 0001.