How do you set the "copyright year" dynamically in Pages?
Hello everyone, I am deploying a static website on Cloudflage Pages and want to dynamically set the copyright year so I don't have to update every year (2024, 2025 etc). When I deploy it shows year 1970. Locally it works fine as it's picking up the year on my machine which is correct.
9 Replies
how is it setting the year right now?
I have attempted two things so far:
1. Setting a const
and passing that to
2. Updated my package.json with a postinstall like so:
then similarly to #1,
and passing that to
If you're doing this at build time, both should be fine, container will be the current time - there's nothing special to set the time to 0
if you are doing new Date at runtime then it could be 0 if done in the global scope
The postinstall script runs during the build process but neither return the correct year.
the postinstall does but if
const currentYear = process.env.BUILD_YEAR || new Date().getFullYear();is executing in runtime and it isn't finding BUILD_YEAR, then it still makes sense
year is definitely right in the container
Thank you very much for confirming, @Walshy | Out of office !
I'll hardcode the year for now and will revisit at a later stage. I am happy to mark this as resolved.
Hey, you dont need to hard code the year, just use plain javascript for it in the frontend side, add a js file in your static files, add the script in all pages that you want to show the actual year and add an id in a span so that it render the year automatically like this:
js file:
let currentDate = new Date();
let currentYear = currentDate.getFullYear();
let currentYearElement = document.getElementById("currentYear");
currentYearElement.textContent = currentYear;
and then in the footer script on each html static file:
<div class="footer-2">
<p class="footer-2-p-text-1">
Copyright <span id="currentYear"></span> | Copyright | Website name etc
</p>
... etc
and then:
<script src="/js/year-code.js"></script>