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
Walshy
Walshy5d ago
how is it setting the year right now?
dok
dok5d ago
I have attempted two things so far: 1. Setting a const
const currentYear = new Date().getFullYear();
const currentYear = new Date().getFullYear();
and passing that to
copyrightText: `© Foo ${currentYear}`
copyrightText: `© Foo ${currentYear}`
2. Updated my package.json with a postinstall like so:
"scripts": {
"postinstall": "echo 'BUILD_YEAR=$(date +%Y)' >> .env"
}
"scripts": {
"postinstall": "echo 'BUILD_YEAR=$(date +%Y)' >> .env"
}
then similarly to #1,
const currentYear = process.env.BUILD_YEAR || new Date().getFullYear();
const currentYear = process.env.BUILD_YEAR || new Date().getFullYear();
and passing that to
copyrightText: `© Foo ${currentYear}`
copyrightText: `© Foo ${currentYear}`
Walshy
Walshy5d ago
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
dok
dok5d ago
The postinstall script runs during the build process but neither return the correct year.
Walshy
Walshy5d ago
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
Walshy
Walshy5d ago
year is definitely right in the container
dok
dok5d ago
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.
felipe1
felipe15d ago
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>
Want results from more Discord servers?
Add your server