Fablezim
Fablezim

Reputation: 23

Redirect if date in URL is later than current month

I am trying to display a page if today's date is current or in the past by reading the current pages URL and looking for keywords. For example,

Sample URL: http://www.website.com/blog/2019/october.html

I would like to write a script that finds the month ("October") and year (2019) from the URL of the page and determines if it is current or in the past. If it is in the future, it will redirect them to an error page, current or past will let them through. The purpose of this is I am pre-publishing pages that I don't want the user to be able to access until it is current content.

I am currently using window.location.href.includes to find a value in the URL, then compare against an array using a loop to return a month and year number. My code so far:

// Sample URL: http://www.website.com/blog/2019/october.html

var monthName = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var monthNum = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

for (i = 0; i < monthName.length; i++) {
    if (window.location.href.includes(monthName[i]) > 0) {
        var pageMonth = (monthNum[i]);
    }
    else {
    }
}

This will give me a result of 10. I was then going to do the same with the year, then make another statement that combines them into a date, then use another statement to determine if thatDate <= currentDate. Is there a better way to execute this?

This method is a mess and it seems like I might be missing something that makes this easier to achieve.


UPDATE: Thank you for all your responses. I have finished my code which is still preferable since it does not depend on the structure of the URL, instead it will just search it all in case I need to move files around or make this work somewhere else as well. I think it could definitely use some cleaning up (especially the two-digit month sections) but I wanted to post it here.

var d = new Date();
var monthTwoDigit = ("0" + (d.getMonth() + 1)).slice(-2);
var monthName = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var monthNum = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];

for (i = 00; i < monthName.length; i++) {
    if (window.location.href.includes(monthName[i]) > 0) {
        var pageMonth = monthNum[i];
    }
    else {
    }
}

for (i = 2019; i < 3000; i++) {
    if (window.location.href.includes(i) > 0) {
        var pageYear = (i);
    }
    else {
    }
}

var urlDate = "" + pageYear + pageMonth;
var actualDate = "" + d.getFullYear() + monthTwoDigit;

if (urlDate > actualDate) {
    window.location.replace("http://www.website.com/error.html");
}
else {
    document.write("SAFE");
}

Upvotes: 1

Views: 362

Answers (3)

Varunkumar Gande
Varunkumar Gande

Reputation: 599

Use an if condition

For example, let the source be: http://www.website.com/blog/2019/october.html

Get currMonthNo and curryear from

var d = new Date();

and also get srcMonthNo from sourceurl

Now check

if(source.indexof(curryear) > -1 && currMonthNo <= srcMonthNo) {
  // Then return your conditional code
} else {
  // Return error message
}

Upvotes: 0

Andrey Kostenko
Andrey Kostenko

Reputation: 382

Yes, this code can be improved in a number of ways. Also, to compare dates we are going to use Date instance, which is built-in JS approach to deal with date and time.

var monthName = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];

First of all, we don't need to list month numbers because we can use array indexes of the array above (from 0 to 11), it will give us the benefit in the future.

Now let's parse month and year from the URL. We are going to use regular expressions to write less code:

const matches = window.location.href.match(/http:\/\/www.website.com\/blog\/([0-9]{4})\/([a-z]{3,})\.html/);

// String.prototype.match, which we used can give us null value if URL doesn't match our pattern, so we need to check it first. 
if (matches !== null) {
  const year = parseInt(matches[0]); // the first match of regular expression is the year
  const monthIndex = monthName.indexOf(matches[1]); // this should give us the number of month, from 0 to 11
  if (monthIndex !== -1) { // but we must continue only if month name in the URL is correct.
    const date = new Date(); // Get current date.

    // Now let's extract month and year from the current date.
    // date.getMonth() returns the current number of month from 0 to 11, just what we need.
    // date.getFullYear() obviously returns the current year number.
    // Let's use these methods and compare current date values with ones we've got from the URL:

    if (date.getFullYear() > year || (date.getFullYear() === year && date.getMonth() > monthIndex)) {
      // we're in the future, let's redirect:
      window.location.href = 'https://website.com/error.html';
    }
  }
}

Upvotes: 2

RobG
RobG

Reputation: 147413

I'd do it pretty much as you've specified. Clear, obvious logic is the easiest to maintain.

function isFutureURL(url) {
  // Month name array
  let months = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];

  // Parse the URL for the year and month
  let b = url.split(/\/|\./);
  let y = b[6];
  let m = months.indexOf(b[7]);

  // Set URL date to 00:00:00 at start of URL month
  let urlDate = new Date(y, m, 1);

  // Return true if test date is after current date
  // I.e. it's the first of next month or greater
  return urlDate > Date.now();
}

['http://www.website.com/blog/2018/april.html',
 'http://www.website.com/blog/2019/october.html',
 'http://www.website.com/blog/2020/may.html'
].forEach(sampleURL => 
  console.log(sampleURL + '\n is in the future? ' + isFutureURL(sampleURL))
);

This assumes that the month and year will always be in the same place in the URL, you might want to consider options to make that more robust (e.g. look for a month name and valid year anywhere in the URL).

You also might want to do some validation of the URL and values of y and m to avoid the user seeing errors.

Upvotes: 1

Related Questions