Skip to Content

Devin Clark

Star Dates in JavaScript

While on my winter vacation, I began creating problems to solve out of boredom and to keep my JavaScript skills sharp. One evening, after an unknown amount of whiskey, I decided to look into converting dates into Stardates. TREKKIE ALERT! Don’t let this discourage you from reading. There still is a decent amount of information JavaScript Dates that can be extracted from this article.

After a bit of research I found that stardates don’t really exist (yet). That was a bit of a disappointing dead end but I found Julian Days to be about the closest equivalent. I assume we will use these in place of stardates in the future. Anyways, I started researching Julian Days, lots of Stack Overflowin’, and (SPOILER ALERT) I eventually got a working converter build.

The first hurdle I had to solve was figuring out the OMG MATH aspect of the formula I found. This was solved by finding a different formula that worked with seconds rather than ALL THE UNITS. This new formula also made conversion to UTC easier, because Julian Days are always calculated using UTC time.

var JD = EPOC_SECONDS / 86400000 - TIMEZONE_OFFSET / 1440 + 2440587.5;

Now, we have a working formula. Let’s plug it in as a JavaScript Date() method. Yes, before you get all up in arms, I am going to use Date.prototype.toStarDate. The day this causes a collision will be a very happy day for me, should that day ever come.

Date.prototype.toStarDate = function () {
return this / 86400000 - this.getTimezoneOffset() / 1440 + 2440587.5;

I originally was rounding the result to two decimal places I later realized that would produce an incorrect Julian Day. I am still skeptical whether JavaScript floating point math is an issue here. It would probably be worth integrating something like BigDecimal.js but that seems out of scope for a whiskey-fueled “just for funzies” project.

Here is a possibly working demo link. If you made it this far, I salute you.

Photo of Devin Clark
Devin Clark
Principal Software Engineer, Oracle
You Might Also Like