I'm currently working on a intranet application.
It shall have a GUI on which you can choose a weekday and a positive / negative integer. The integer stands for weeks.
So let's say someone chooses the Wednesday and (-7) then it shall display the date of the Wednesday seven weeks ago.
Tuesday and 3 => Tuesday in three weeks.
Here's the code which shall calculate the date:
// Returns a Date Object which contains
// the date before/in n-days and
// before/in n-weeks.
// -- Parameter ----------------------------
// 1. String - The desired weekday as an
// abbreviation.
// Assign for ...
// Monday : 'mo'
// Tuesday : 'tu'
// Wednesday : 'we'
// Thursday : 'th'
// Friday : 'fr'
// Saturday : 'sa'
// Sunday : 'su'
// 2. Number - Positive number => n-weeks in
// the future.
// Negative number => n-weeks before.
// -- Return -------------------------------
// (Date) Object
function getDayBeforeIn(day, weeks) {
var currentDate = new Date();
var currentStamp = currentDate.getTime();
var weekdays = {
'mo': 1,
'tu': 2,
'we': 3,
'th': 4,
'fr': 5,
'sa': 6,
'su': 0
}
var milliSecondsDay = 24 * 60 * 60 * 1000;
day = day || 'mo';
weeks = weeks || 0;
currentStamp += weeks * 7 * milliSecondsDay;
currentStamp +=
(weekdays[day] - currentDate.getDate()) *
milliSecondsDay;
return new Date(currentStamp);
}
// Returns the Day, Month, Year of an
// JavaScript Date Object as as String
// in the Date format DMY.
// -- Parameter ----------------------------
// 1. Date-Object
// 2. String - Is used for separating
// Day-Year and Month-Year.
// -- Return -------------------------------
// String
function getDayMonthYearDate(dateObject, separator) {
var day = '0' + dateObject.getDate();
var month = '0' + (dateObject.getMonth() + 1);
var year = dateObject.getFullYear();
separator = separator || '.';
return day.slice(-2) + separator +
month.slice(-2) + separator + year;
}
// -- TEST -----------------
for (var i = 0; i < 10; i++) {
var result = getDayBeforeIn('th', i * (- 1));
console.log(getDayMonthYearDate(result));
}
/* -- Results ---
04.02.2016
28.01.2016
21.01.2016
14.01.2016
07.01.2016
31.12.2015
24.12.2015
17.12.2015
10.12.2015
03.12.2015
*/
All suggestions and hints concerning improvements welcome.