How to convert the current time to a hexadecimal

Posted January 9, 2017

Taken by Team UI8

It’s actually really easy, Demo.

This is a pretty basic one function website, the function runs every second and takes the time in military time and then outputs that as a hex, while changing the background color to it.

1const setDate = () => {
2 // get the datetime
3 const now = new Date();
4 // get hours from our "now" variable
5 const hours = now.getHours();
6 // get minutes from our "now" variable
7 const minutes = now.getMinutes();
8 // get seconds from our "now" variable
9 const seconds = now.getSeconds();
10 // select our h1 element
11 const text = document.querySelector('h1');
12
13 // group our 3 variables above to make the time with a hash in front
14 const hexTime = `#${hours}${minutes}${seconds}`;
15
16 // make the text of the text variable the content of hexTime variable above
17 text.textContent = hexTime;
18
19 // style the body background color to be the hex color
20 document.body.style.background = hexTime;
21
22 setInterval(setDate, 1000);
23};

Not so fast, you’re not done yet! Notice when the time is 9:03:03 or any time that's less than 10, the hex is only then 3 numbers, which is fine, until you get 4 or 5 digits. So to resolve this you can adjust the function like so:

1const setDate = () => {
2 // get the datetime
3 const now = new Date();
4 // get hours from our "now" variable
5 const hours = now.getHours() < 10 ? '0' + now.getHours() : now.getHours();
6 // get minutes from our "now" variable
7 const minutes =
8 now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes();
9 // get seconds from our "now" variable
10 const seconds =
11 now.getSeconds() < 10 ? '0' + now.getSeconds() : now.getSeconds();
12
13 // or thanks to string.padStart in es2017, we can shorten this to:
14 const hours = String(now.getHours()).padStart(2, '0');
15 const minutes = String(now.getMinutes()).padStart(2, '0');
16 const seconds = String(now.getSeconds()).padStart(2, '0');
17
18 // select our h1 element
19 const text = document.querySelector('h1');
20
21 // group our 3 variables above to make the time with a hash in front
22 const hexTime = `#${hours}${minutes}${seconds}`;
23
24 // make the text of the text variable the content of hexTime variable above
25 text.textContent = hexTime;
26
27 // style the body background color to be the hex color
28 document.body.style.background = hexTime;
29
30 setInterval(setDate, 1000);
31};

Now what that’s doing is running a ternary to see if the time is less than 10 or not if it is, then it prepends a 0 to the variable.

Woohoo! You now have a clock that shows you hexadecimal colors. You can even change the android chrome theme color every second:

1document.querySelector('meta[name="theme-color"]').content = hexTime;