How to Check the Current Time with JavaScript
Nathan Pasko
Posted on January 31, 2021
This series is all about expanding our definition of responsive design. At its core, responsiveness is all about adapting a design to its context, but that context can mean a lot more than a device's screen size; we're brainstorming to respond to light & dark display modes, location, and now, the current time and date.
The Date Object
JavaScript has a built-in type called Date that encapsulates a moment in time. Date objects also have built-in methods to manipulate them, but even so, the JavaScript Date object is considered a bit broken by our community. It can be difficult to use, but I've seen promising alternatives on the horizon, and for our purposes today we can stick to Date's most basic features.
Let's build up an example web page to demonstrate how to make a design respond to the current time. All we need to start is a fresh HTML page.
How to Check the Current Time and Date in JavaScript
In JavaScript a constructor is a special function that creates a new instance of a class. By using the basic Date constructor, we can get a Date object representing the current time. We can use console.log()
to try it out; we'll log the time that we refresh the page.
// Use Date constructor to get current time
var now = new Date();
console.log(now);
Since a Date object encapsulates so much data, all describing a single moment, Date provides a number of functions that we can use to grab a single slice of that data. For example, Date.getMinutes()
and Date.getHours()
will return just the minutes or hours values of the Date object respectively.
// Get just the hours or just the minutes
console.log(now.getHours());
console.log(now.getMinutes());
// Use a colon to log a clock-like readout
console.log(now.getHours(), ':', now.getMinutes());
We'll make use of Date.getHours()
in particular to demonstrate a time-based responsive design.
How to Write a Simple Responsive Design Using Time
Let's use JavaScript and CSS together to create a responsive design using Date. We'll change the background color of the page in accordance with he current time of day. First things first: let's give ourselves a <div>
called #container
to ensure we have control over the page background. We'll add some CSS styles to the container in a moment.
<div id="container"></div>
Morning, afternoon, evening, and night will each have their own corresponding background color. Our approach will be to check the current time upon page load, use Date.getHours()
to infer which time period we're currently in, and then set the answer to a data attribute in order to apply the correct styles.
In our stylesheet, we'll first guarantee the container fills the page for visual effect, and then we'll write style rules that hinge on an attribute called data-time
.
#container {
height: 100vh;
width: 100%;
}
#container[data-time="morning"] {
background: pink;
}
#container[data-time="afternoon"] {
background: aqua;
}
#container[data-time="evening"] {
background: blue;
}
#container[data-time="night"] {
background: black;
}
Back in our JavaScript, we need a reference to our container element, so we'll declare that. Now we'll add a small array of data that describes the four times of day that we want to work with, including their start and end.
// Grab container element
const container = document.getElementById('container');
// Times of day data
const times = [
{ name: 'morning', start: 4, end: 12 },
{ name: 'afternoon', start: 12, end: 17 },
{ name: 'evening', start: 17, end: 20 },
{ name: 'night', start: 20, end: 23 }
];
That array of times of day will help us figure out what time we're currently in. Let's use a variable called currentTime
to hold the current time of day. Because of the way night wraps around multiple days, complicating the logic, let's set the default value for currentTime
to night.
// Use times array to default time to night
var currentTime = times[3];
Using night as our default value will let us write simpler code checking just the other three times of day.
Finally, we'll write a for
loop to complete the example. Since we have night set as our default time, we only need to iterate through the first three objects in our times
array. To find the correct time of day we'll compare the hours value of our Date object to the start and end times of each time of day. The hours value will be greater than or equal to the start value of the current time of day, and less than its end value. Our for
loop will iterate through the data in our array, and when it reaches the correct time of day, it will store the answer in currentTime
and set our container div's data-time
attribute accordingly.
// Grab hours from Date object
const hours = now.getHours();
// Iterate through times of day
for (var i = 0; i < 3; i++) {
// If this time of day matches
if (hours >= times[i].start && hours < times[i].end) {
// Store correct time of day
currentTime = times[i];
// Communicate time of day to styles via data attribute
container.dataset.time = currentTime.name;
}
}
Now we have a basic responsive design that reflects the time of day! When we reload the page, the container's background color sets itself accordingly.
Final Thoughts
The example above proves how simple it can be to respond to current time in our designs. Responsiveness based on screen size is everywhere now, but other kinds of responsive design are more scarce. Let's take our expanded definition of responsiveness out into the world and create more interactive designs!
A note about the JavaScript Date object before we go. The Date object was sufficient for today's example, but it can be difficult to work with when we get more in depth. There are alternatives out there; moment has proven to be a mainstay and it's so easy to use that I think it's worth a look. I think there's great value in familiarizing oneself with vanilla JavaScript's many features (I recently penned a series of examples of jQuery operations written in vanilla JS), but Date is often the first exception to that rule that I make in any project. Sometime last year I read about a promising proposal for a replacement for Date called Temporal which probably deserves some attention. All of this is to say that Date can be tricky, and while I usually prefer to paint JavaScript as a forgiving language for beginners, Date is a place where I don't think there's any shame in acknowledging the off-putting implementation provided by vanilla JavaScript.
Though the state of date and time in JavaScript is complicated, the main idea behind this article is to expand what we think about when we consider the term "responsive." If you were following along with the code, you felt how quick and easy it is to tap into the current time and date. Let these ideas percolate and see what new kinds of responsive designs you're able to create!
Posted on January 31, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
July 27, 2022