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
Walshy2mo ago
how is it setting the year right now?
dok
dokOP2mo 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
Walshy2mo 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
dokOP2mo ago
The postinstall script runs during the build process but neither return the correct year.
Walshy
Walshy2mo 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
Walshy2mo ago
year is definitely right in the container
dok
dokOP2mo 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
felipe12mo 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