I’m trying to put together a JavaScript function (and it has to be pure JavaScript, can’t use PHP or MySQL) to work out how many weeks between two dates. We have a twelve week roster and I want to work out where in the roster each person will be on a given date (and week).
I have a function to create a date object for each:
//Converts a string into a date
function calcDate(strDate) {
//Trim any extra spaces
strDate = strDate.trim( )
//Change all the delimiters to a stroke
strDate = strDate.replace(/ /g,"/");
strDate = strDate.replace(/\\ /g,"/");
strDate = strDate.replace(/\-/g,"/");
strDate = strDate.replace(/\./g,"/");
var intYear = strDate.slice(strDate.lastIndexOf("/") + 1);
var intMonth = strDate.slice(strDate.indexOf("/")+1,strDate.lastIndexOf("/"));
var intDay = strDate.slice(0, strDate.indexOf("/"));
return new Date(intYear,intMonth-1,intDay);
}
I then use the code below to work out how many weeks there are between two dates:
//Create a variable for a day in milliseconds
var dayLength = 1000*60*60*24;
//Get the date input by the user and the roster start date
var chosenDate = calcDate(document.getElementById("txtDate").value);
var startDate = calcDate(document.getElementById("txtStartDate").value);
//Work out the difference in weeks
var intWeeks = Math.floor(((chosenDate-startDate)/dayLength)/7);
//Divide by link size and get the remainder to simplify the maths
intWeeks = intWeeks % linkSize;
//Display the new Date
document.getElementById("newDate").innerHTML = emptyString.concat("<p>The date you have selected is: ", chosenDate, ", ", intWeeks, " weeks into the cycle.</p>");
This works fine, except of course when BST comes into play - on the first day of BST, although the last bit (display the date) shows the right date, it is doing it’s calculations based on GMT, so it thinks it’s 23:00 the previous day and therefore it thinks we are a week behind in the roster cycle.
Have I missed something stupid?
Thanks
Chris