Advertisement
Web Developer Resources
You Are Here: ESQSoft.com ¬ javascript_examples ¬ Date/Epoch Time Converter - Javascript tools - Learning examples
E.S.Q. Software Logo

Date/Epoch Converter

Option 1: Enter a human readable date (MM/DD/YYYY HH:MM:SS)
Date: ::
Option 2: Enter an epoch time value
Epoch Time Value:
Conversion Output: (the result of your input will appear here)
...

GMT (if unchecked, it uses your local time without attempting the offset.)

Current Time (from your computer)

Current Date/Time: (JavaScript)

1732183041 (Epoch)
Thu Nov 21 2024 09:57:21 GMT+0000 (Coordinated Universal Time) (Standard)
Current Date/Time: (PerlScript1)

(Sorry, it doesn't appear that you have PerlScript installed.)

This section shows the output of two client-side scripting languages: JavaScript and PerlScript.

Why JavaScript? It's arguably the de facto standard for client-side scripting on the web, winning out over VBScript, Flash/Actionscript, even client-side PerlScript (*sigh*). Even modern competitors such as Typescript must be compiled to Javascript to run on most browsers.

1 Why PerlScript? Mostly as an interesting aside (something from a past use case which serves as a cautionary tale). TLDR, it's a bad idea. Still curious? Perhaps this topic on stack overflow would be of interest.

What is epoch

Roughly speaking, epoch is the time in seconds that have elapsed since computers started counting. For our purposes we'll call that 0 hours, 0 minutes, 0 seconds starting from January 1, 1970. If interested in more info, I defer to this article about epoch definition.

Epoch is useful in computer programming because we can use it to compare dates mathematically which helps us write programming logic with it by converting a human-readable date format into its equivalent in epoch.

How to Convert between Date and Epoch

I've had many questions about how to do the conversion. It's worth viewing the source code here to understand... if only to find how not to do it. ;-) But, since this topic isn't specifically a programming concern, I'll take a stab at explaining what the code does in english (or as near to it as I can manage, apologies to my teachers in advance).

First off, the easiest way to get the current time in epoch (using JavaScript), is to call getTime() method of the JavaScript Date object and divide the return value by 1000. getTime returns the number of milliseconds elapsed, in your computer's timezone, since 1/1/1970 GMT. Because epoch is measured in seconds, you then want to divide the return value by 1000 to change milliseconds into seconds. Keep in mind that the JavaScript Date object will get it's time from your computer's clock. Here's a really simple example doing this.

Click to Show Current Epoch Time <script type="text/javascript"> function epochExample1() { var d = new Date(); prompt('Cut/Paste into the converter to Test', (d.getTime() - d.getMilliseconds()) / 1000); } </script> <a href="#" onclick="epochExample1(); return false;">Click to Show Current Epoch Time</a>
Note: We're subtracting the milliseconds in order to get a whole number instead of a fraction. You could probably use parseInt similarly, in fact, here's another mini-example demonstrating the differences between (a) getTime()/1000 alone -- sometimes a fraction is returned, (b) method above, (getTime - milliseconds)/1000, and (c) parseInt(getTime/1000).
Click to test <script type="text/javascript"> function testMethods1() { // testing differences between getTime/1000 vs. subtracting milliseconds vs. parseInt(getTime/1000) var d1 = new Date(); var d1t0 = d1.getTime() / 1000; var d1t1 = (d1.getTime() - d1.getMilliseconds()) / 1000; var d1t2 = parseInt(d1.getTime() / 1000); var msg = 'Testing various methods:' + '\n1) Date.getTime()/1000 = ' + d1t0 + '\n2) (Date.getTime()-Date.getMilliseconds())/1000 = ' + d1t1 + '\n3) parseInt(Date.getTime()/1000) = ' + d1t2 alert(msg); return false; } </script> <a href="#" onclick="return testMethods1()">Click to test</a>
Tools are all well and good, but I like pain, how do you do this manually?

Hmmm okay... if you have a human-friendly date/time that you want to convert but you are, shall we say "tool averse" (or you just enjoy mental gymnastics--good for you, btw), I'll take a stab at explaining a process for doing this manually.

Keep in mind that an accurate description of what the JavaScript Date Object methods are doing isn't in scope--rather my effort to explain will be conceptual.

You could do a rough calculation as follows:

For kicks and giggles let's use for our example a day that many folks will recognize, April 15, 2025. And, we'll say it's 08:30 in the morning just to add some spice to this effort.

Years

Start with the year: 2025. Subtract out 1970 from the year. 2025 - 1970 leaves us with 55 years. (Sanity check)

Convert the years to days. So 55 years multiplied by 365 days in each of those years. This gives us 20075 days.

Now the first relatively difficult issue--dealing with leap years. Like me, you may have had it explained to you that roughly every four years can be a leap year...with some caveats. Actually, (as a helpful individual has pointed out to me) the real rule is as follows: Years that are evenly divisible by 100 are not leap years, unless they are also evenly divisible by 400, in which case they are leap years, bringing the total number of days in that year to 366.

We need to examine each of the 55 years between our target and the 1970 starting point. (This is one reason a tool is so great. You don't have to brute force the effort.) Writing a quick script to determine the calculation...

The number of extra days due to leap years between 1970 and 2025 is [14] days. Leap years in the range are: 2024, 2020, 2016, 2012, 2008, 2004, 2000, 1996, 1992, 1988, 1984, 1980, 1976, 1972 <script type="text/javascript"> /* note: syear variable set in earlier script -- it's the starting year from our example */ function isLeapYear(year) { if (!year.toString().match(/[0-9]{0,4}/)) { /* invalid input */ return false; } if ((year % 4) == 0) { if ((year % 100) == 0) { if ((year % 400) == 0) { return true; } else { return false; } } else { return true; } } else { return false; } } var leap_days = 0; var str = 'Leap years in the range are: '; for (var i = syear; i > 1970; i--) { if (isLeapYear(i)) { leap_days++; str += '' + i + ', '; } } str = str.replace(/,\s$/, ''); document.write('The number of extra days due to leap years between 1970 and ' + syear + ' is [' + leap_days + '] days. '); document.write(str); </script>The number of extra days due to leap years between 1970 and 2025 is [14] days. Leap years in the range are: 2024, 2020, 2016, 2012, 2008, 2004, 2000, 1996, 1992, 1988, 1984, 1980, 1976, 1972

Want to sanity check whether a specific year is a leap year? (Uses algorithm in isLeapYear function code example above to calculate leap year.)

So, we need to add 14 to our original 20075 which brings us to 20089 total days so far .

Months in Days

Now we need to factor in the months in the current year and convert to days. In our example, we're using April 15, so we have 15 days for the current month. January has 31 days, February has 28--unless this year is a leap year in which case it has 29. If this is a leap year, we caught it in our leap year check above. March has 31 days. Adding these up we get 15 + 31 + 28 + 31 = 105 days. Adding that back in to our running total of days we get 20089 + 105 = 20194

Now that we've got all of the days, let's convert those to seconds. It turns out that there are roughly 86,400 seconds in each day. (See the chart below for more useful conversions.) So we take 20194 and multiply it by 86400 to get 1744761600 seconds which have elapsed up until the beginning of April 15.

Hours, Minutes, ...Seconds?

Now we need to factor in the hours and minutes that have passed in the current hypothetical day. It's 08:30. In each minute there are 60 seconds, in each hour there are 60 minutes, so we convert the 8 o'clock hour as 8 * 60 * 60. This gives us 28800. Further, we'll convert the 30 minutes since the 8 o'clock hour into seconds, 30 * 60 which gives us 1800. And we add those all back into the seconds so far to get 1744792200

Add a dash of craziness...

Lastly, we need to calculate our offset from GMT. Hmmm... and then factor in daylight savings (*more sigh*). In my case, PST, we're 8 hours different--and we participate in daylight savings. So I add (8 * 60 * 60) + (1 * 60 * 60) which gives 32400, back into my running seconds to get my local time. 1744824600

This should be the epoch time we're looking for. (See sanity checking your results below.) So, we're saying 1744824600 seconds have elapsed since 1/1/1970--"0" in computer time. It's not very friendly for human eyes, but then it's intended for computers; because we can use math now to compare it with other dates--a common problem in programming-related applications.

Sanity checking your results

Plug 1744824600 back into the converter and see how far off our target date you are. It's likely that you are off by some amount, probably the offset for your own local timezone. In general, you should always sanity check your results. Two good tests are, checking your results against today (using the current epoch from getTime/1000 for example), and "0" time. If your mechanism passes both tests, that's a good sign.

Another interesting note: I've heard folks suggest using UTC rather than local time. UTC is certainly an appropriate "global" approach to time based applications, particularly when your audience spans the globe; In that case, having a standard time to fallback on is excellent. In order to apply it to your specific locale, you would calculate the target timezone offset from UTC. There are some strange issues that come up. Calculating an offset accurately can be really tough in the real world. For example, Arizona time while correct in Windows, isn't correct in JavaScript. And that's just one example. I'm not an expert on timezones, so I don't know how prolific timezone offset problems are. I'd appreciate feedback from anyone in the know.

Examples of Usage

Of course, the most relevant question in all of this is "why would I want to do any of this?" I've had the need for this arise many times. One notable example which occurred while working for a web hosting company was that we wanted to turn messaging chunks on/off 3 days after a new signup for services. We had a marketing manager that wanted to play some messaging to our audience of webmasters three days into their experience. Because there is a steady inflow of customers, the exercise is an ongoing one, and relative to each specific account. We needed a way to identify a member of the 3+ day audience and then some logic to trigger the messaging. In turning that need into programming routines, we did the following steps.

  1. First, we stored the epoch value of the date of each signup (for example, Jan 1, 2003 is 1041459471 in epoch). Now that the date value is an integer, we can do math with it.
  2. Second, we calculate 3 days in epoch measures (seconds) as follows... (86400 * 3)
  3. Third, compare the current time with the signup time, plus the 3 days epoch value.

By making signup date a variable, this rule can apply to anyone for whom we want to know 3 days into the future of their signup.
ex: $signup_date = 1041459471 (or whatever the epoch is for any given site)

if ($current_time > ($signup_date + (86400 * 3))) { 
  /*  ...then this site was signed up more than 3 days ago
        show them the relevant message
  */
}

Common Time Measures in Epoch

1 Millisecond = 1/1000 in Epoch (used frequently with JavaScript conversions)
1 Second = 1 in Epoch
1 Minute = 60 in Epoch
10 Minutes = 600 in Epoch
1 Hour = 3600 in Epoch
6 Hours = 21600 in Epoch
12 Hours = 43200 in Epoch
1 Day = 86400 in Epoch (24 Hours)
1 Week = 604800 in Epoch (7 Days / 168 Hours)
1 Month = (see below... number of days in the month)
 28 Days = 2419200 in Epoch (672 Hours)
 29 Days = 2505600 in Epoch (696 Hours)
 30 Days = 2592000 in Epoch (720 Hours)
 31 Days = 2678400 in Epoch (744 Hours)
 AVERAGE MONTHS IN YEAR = 2628000 in Epoch
  (365 / 12 = 30.416666666666666666666666666667) (average months)
  (30.416666666666666666666666666667 * 86400 = 2628000) (average months in Epoch)
1 Year = 31536000 in Epoch (365 days * 86400 seconds)

Source Code for Converter and Examples

<script type="text/javascript"> /* Date/Epoch Functions Author: Thomas Ballard (http://thomas.ballard.ws) (TODO: Ugh, 1999 called and it wants you to update your javascript!) Note: slightly polluted to attempt to support a GMT/non-GMT (local) timezone offset feature. Hack and slash resulted in a form input having a toggle state... but these functions need to know that form and input to access the property for evaluation. Need to come back and make these methods more agnostic. */ if (!window.dDate) window.dDate = new Date() window.getEpoch = function () { var GMT = document.ivnForm.GMT.checked if (GMT) { var x = parseInt(Date.UTC(dDate.getUTCFullYear(), dDate.getUTCMonth(), dDate.getUTCDate(), dDate.getUTCHours(), dDate.getUTCMinutes(), dDate.getUTCSeconds(), dDate.getUTCMilliseconds()) / 1000); return x; } else { var x = (dDate.getTime() - dDate.getMilliseconds()) / 1000; // x += dDate.getTimezoneOffset(); return x; } } window.getDays = function (mObj, dObj, yObj) { // build array of days in a select container based on selected month and year iMonth = parseInt(mObj.options[mObj.selectedIndex].value) + 1 iYear = (yObj.value ? yObj.value : 1900); var iDays = 31; switch (iMonth) { /* determine the number of days this month including leap years */ case 4: case 6: case 9: case 11: --iDays; break; case 2: iDays = 29; if (!((iYear % 4 == 0) && (iYear % 100 != 0)) || (iYear % 400 == 0)) --iDays; } dObj.options.length = 0; for (var i = 0; i < iDays; i++) { dObj.options[i] = new Option(i + 1, i + 1) } } window.toDate = function (eObj) { var mEpoch = parseInt(eObj.value); if (mEpoch < 10000000000) mEpoch *= 1000; // convert to milliseconds (Epoch is usually expressed in seconds, but Javascript uses Milliseconds) dDate.setTime(mEpoch) return dDate; } window.toEpoch = function (mObj, dObj, yObj, hrObj, minObj, secObj) { var month = mObj.options[mObj.selectedIndex].value var day = dObj.options[dObj.selectedIndex].value var year = yObj.value var hour = hrObj.options[hrObj.selectedIndex].value var minute = minObj.options[minObj.selectedIndex].value var second = secObj.options[secObj.selectedIndex].value //alert(month+']['+day+']['+year) dDate.setMonth(month, day) dDate.setFullYear(year) dDate.setHours(hour, minute, second) //alert(dDate) var zObj = document.getElementById('dynamo') zObj.innerHTML = window.getEpoch() if (window && window.clipboardData && window.clipboardData.setData) bResult = window.clipboardData.setData("Text", zObj.innerHTML); //stuff the text onto the clipboard } </script> <script type="text/javascript"> function populateDates() { var fobj = document.forms.ivnForm if (fobj.GMT.checked) { // GMT TIME window.dDate = new Date(Date.UTC(dDate.getUTCFullYear(), dDate.getUTCMonth(), dDate.getUTCDate(), dDate.getUTCHours(), dDate.getUTCMinutes(), dDate.getUTCSeconds(), dDate.getUTCMilliseconds())); fobj.month.selectedIndex = dDate.getUTCMonth(); // set initial month to current fobj.year.value = dDate.getUTCFullYear() getDays(fobj.month, fobj.day, fobj.year) fobj.day.selectedIndex = dDate.getUTCDate() - 1 fobj.epoch.value = window.getEpoch() fobj.hour.selectedIndex = dDate.getUTCHours(); fobj.minute.selectedIndex = dDate.getUTCMinutes(); fobj.second.selectedIndex = dDate.getUTCSeconds(); } else { // LOCAL TIME window.dDate = new Date(); fobj.month.selectedIndex = dDate.getMonth(); // set initial month to current fobj.year.value = dDate.getFullYear() getDays(fobj.month, fobj.day, fobj.year) fobj.day.selectedIndex = dDate.getDate() - 1 fobj.epoch.value = window.getEpoch() fobj.hour.selectedIndex = dDate.getHours(); fobj.minute.selectedIndex = dDate.getMinutes(); fobj.second.selectedIndex = dDate.getSeconds(); } var GMT = document.ivnForm.GMT.checked if (GMT) { var html = parseInt(Date.UTC(dDate.getUTCFullYear(), dDate.getUTCMonth(), dDate.getUTCDate(), dDate.getUTCHours(), dDate.getUTCMinutes(), dDate.getUTCSeconds(), dDate.getUTCMilliseconds()) / 1000) + ' (Epoch)' + '<br>' + dDate.toUTCString() + ' (Standard)' } else { var html = (dDate.getTime() - dDate.getMilliseconds()) / 1000 + ' (Epoch)' + '<br>' + dDate + ' (Standard)' } if (document && document.getElementById) { obj = document.getElementById('jdate1') if (obj) obj.innerHTML = html } } populateDates(); </script> <script type="text/perlscript"> $obj = $window->document->getElementById('pdate1'); $obj->{innerHTML} = time . " (Epoch)<br>" . localtime(time) . " (Standard)"; </script>
Advertisement
Advertisement
StatCounter - Free Web Tracker and Counter