One of the things that we can do with JavaScript is display and manipulate the date and time. This can be useful in many ways, such as calculating the days between dates, showing new items on your Web site and calculating shipping dates. In this installment we’ll take a look at the JavaScript Date() object and learn how to utilize it in our scripts.
Living on JavaScript Time
JavaScript uses the date of midnight, January 1, 1970 UTC as a starting point for all of its calculations (also the same date used by Unix and Java). Since it’s the starting date from which Unix time is measured, it’s known as the Unix epoch, epoch time, or just the epoch. Anything prior to that date is declared as a negative value. While we might calculate the days between two calendar dates, the numbers used in the calculations are determined by the number of milliseconds that have passed since the epoch time (not counting leap seconds).
All epoch time is measured in units of milliseconds. To ensure accuracy, all calculations should be performed on that basis. These calculations are done using the getTime() method. For instance, using a specific time — Friday, September 22, 2006, 3:57:12 PM, we can calculate the time as 1,158,955,032,531 milliseconds from January 1, 1970. (Boy, time sure flies!) In order to determine how many years it’s been since the epoch, we could use the following calculation:
That will return a value of 36.75023885004439 (using our date above). That would be 36 years, 8 months, and 21 days. (I used another script to get the exact amount of time.) Here’s how it works (this is a rough calculation and doesn’t account for leap years):
First, we created a new instance of the Date() object and gave that value to the newly created variable d
Next, we used the getTime() method of the Date() object to obtain the time from the variable d.
Then, we created a variable named days and gave it the value of the calculation that follows it.
First, we took the variable e and divided it by 1000 — because the time is in milliseconds, which gives us the number of seconds.
Then we divided that number by 60 — the number of seconds in a minute.
Next we divided that number by 60 — the number of minutes in an hour.
Then we divided that number by 24 — the number of hours in a day.
And then we divided that number by 365 — the number of days in a year.
Chance are you’re pretty confused by now so let me try to make it simpler (with some help from Danny Goodman). The following calculations (presented as variables) should make it easier for you to see the relationship.
That should be easier to understand. You can also use that for your own calculations.
Advertisement
The Date Object
JavaScript uses the Date() constructor to obtain and manipulate the day and time in a script. The information is taken from the user’s computer and is only as accurate as the user’s system. It’s important to remember that as it will determine the outcome of your scripts.
It’s possible to manipulate the date using Coordinated Universal Time (UTC), which is basically the same as Greenwich Mean Time (GMT). (Actually, GMT is measured from noon whereas UTC is measured from midnight. However, few use the noon measurement and refer to GMT as if it were actually UTC.)1 That’s a bit beyond our basic tutorial so we won’t worry too much about that now. We’ll look at that later, in a more advanced tutorial.
Note also that the Date() object is case sensitive. Failure to observe that little fact will result in many headaches.
Advertisement
Creating Dates
To use the Date() we need to use the new keyword. If you remember our discussion in Part 11, the new keyword creates a new instance of the object. In this case it means that we take the Date() object, make a copy of it and give that copy a name. It’s a new “instance” or “occurrence” of the Date() object. That would be done like this:
As I said, this creates a new instance of the Date() object. It’s important to remember that it contains the value of the user’s system date at the time of execution. The date/time is not updated unless manipulated by the script. For instance, if I issued the above statement right now, it might contain the date/time data as listed below:
Fri Sep 22200614:29:28 GMT-0400 (Eastern Standard Time)
While this will be fine in many situations, it’s important to remember that, without manipulation, the data is not constantly being updated as the script is running. If we wanted to display the data as is, we could write the following:
which would print as follows:
The date is Friday, September 22, 2006
and the time is 2:29:28 PM
Let’s take a look at what we did here.
First, we declared a new instance of the Date() object (using the new keyword) and gave its value to a newly created variable named d.
Next, we created two document.write statements.
The first one uses the toLocaleDateString() method. (We’ll look at the Date() object’s methods in a moment.) This tells the script to display the date portion of the variable using the format of the user’s computer system.
The second one, toLocaleTimeString(), tells the script to display the time portion of the variable using the format of the user’s computer system.
Let’s take a look at the methods available when using the Date() object. From there we will look at how to apply them.
Introduced in 2015, ES6 (also known as ECMAScript 2015 or ECMAScript 6) was the most impactful revision of JavaScript since ES5 (ECMAScript 5) in 2009. It added a veritable cornucopia of features, including Arrow Functions, the const and let keywords, default parameters, among others. Then ECMAScript 2016, 2017, and 2018 added even more, including the […]
If you have ever examined an Angular app’s file structure, you would find a lot of HTML, CSS, and JavaScript templates that all work together and get compiled to render a well-crafted web application. The compilation process consists of two approaches. The first one is the Just in Time (JIT) compilation, on which Angular relied […]
Sometimes it becomes necessary to convert an object into a string in order to view or store it. For the purpose of debugging, a simple console.log() will suffice, as just about any modern browser’s Dev Tools will provide a pretty printed version of an object. Meanwhile, relying on implicit conversion when writing an object to […]
All programming languages, including JavaScript (JS), have built-in data types; these include strings, numbers, Dates, Arrays, and so forth. What makes JS special is that it is loosely typed. Hence, variables are declared without a type, which allows them to be re-assigned values of a different type at any time. This feature makes the language […]
The original home of HTML tutorials. HTMLGoodies is a website dedicated to publishing tutorials that cover every aspect of being a web developer. We cover programming and web development tutorials on languages and technologies such as HTML, JavaScript, and CSS. In addition, our articles cover web frameworks like Angular and React.JS, as well as popular Content Management Systems (CMS) that include WordPress, Drupal, and Joomla. Website development platforms like Shopify, Squarespace, and Wix are also featured. Topics related to solid web design and Internet Marketing also find a home on HTMLGoodies, as we discuss UX/UI Design, Search Engine Optimization (SEO), and web dev best practices.
Advertiser Disclosure: Some of the products that appear on
this site are from companies from which TechnologyAdvice
receives compensation. This compensation may impact how and
where products appear on this site including, for example,
the order in which they appear. TechnologyAdvice does not
include all companies or all types of products available in
the marketplace.