Skip to content
Advertisement

Redirect website between two specific dates using JavaScript

I’m in need of some help regarding redirecting my website during certain days each year. I want to be able to redirect my website from the current one (A) to the other one (B) between 1st of March to 15th of April.

I can’t find any way to do this without making a weird cluster of websites that loads and redirect the user back and forth to multiple pages. I tried to add certain code in the script and such but no success. I’m trying also to not include a specific year only the dates so it runs same dates each year without modification. The code I use today for the season is:

<script>var date=new Date();
if(date.getMonth()==3){
  window.location="https://www.MYWEBSITE.com/site_B.html"}</script>

which only redirects the full months of April which isn’t optimal at all. All ideas are welcome and I appreciate all help.

Advertisement

Answer

If you’re not concerned about locales and different timezones, you can use this.

let today = new Date().getTime();
// use current year only
let year = new Date().getFullYear();
let s = `${year}-11-15`,  e = `${year}-12-15`
let startDate = new Date(s).getTime();
let endDate = new Date(e).getTime();
if (today >= startDate && today <= endDate) {
  console.log('redirect');
  //window.location="https://www.MYWEBSITE.com/site_B.html";
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement