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 datetime3 const now = new Date();4 // get hours from our "now" variable5 const hours = now.getHours();6 // get minutes from our "now" variable7 const minutes = now.getMinutes();8 // get seconds from our "now" variable9 const seconds = now.getSeconds();10 // select our h1 element11 const text = document.querySelector('h1');1213 // group our 3 variables above to make the time with a hash in front14 const hexTime = `#${hours}${minutes}${seconds}`;1516 // make the text of the text variable the content of hexTime variable above17 text.textContent = hexTime;1819 // style the body background color to be the hex color20 document.body.style.background = hexTime;2122 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 datetime3 const now = new Date();4 // get hours from our "now" variable5 const hours = now.getHours() < 10 ? '0' + now.getHours() : now.getHours();6 // get minutes from our "now" variable7 const minutes =8 now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes();9 // get seconds from our "now" variable10 const seconds =11 now.getSeconds() < 10 ? '0' + now.getSeconds() : now.getSeconds();1213 // 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');1718 // select our h1 element19 const text = document.querySelector('h1');2021 // group our 3 variables above to make the time with a hash in front22 const hexTime = `#${hours}${minutes}${seconds}`;2324 // make the text of the text variable the content of hexTime variable above25 text.textContent = hexTime;2627 // style the body background color to be the hex color28 document.body.style.background = hexTime;2930 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;