Skip to content

Instantly share code, notes, and snippets.

@LoicMahieu
Last active December 10, 2015 21:29
Show Gist options
  • Save LoicMahieu/4494861 to your computer and use it in GitHub Desktop.
Save LoicMahieu/4494861 to your computer and use it in GitHub Desktop.
determineDate(date, refDate, defaultDate) Usage: determineDate('+1y') = now + 1 year determineDate('+1d', new Date(2012, 1, 1)) == 2012-01-02
function determineDate(date, refDate, defaultDate) {
var getDaysInMonth = function (year, month) {
var date = new Date(year, month, 32);
date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
return 32 - date.getDate();
},
offsetNumeric = function (offset, date) {
date.setDate(date.getDate() + offset);
return date;
},
offsetString = function (offset, date) {
var year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate(),
pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
matches = pattern.exec(offset);
while (matches) {
switch (matches[2] || "d") {
case "d":
case "D":
day += parseInt(matches[1], 10);
break;
case "w":
case "W":
day += parseInt(matches[1], 10) * 7;
break;
case "m":
case "M":
month += parseInt(matches[1], 10);
day = Math.min(day, getDaysInMonth(year, month));
break;
case "y":
case "Y":
year += parseInt(matches[1], 10);
day = Math.min(day, getDaysInMonth(year, month));
break;
}
matches = pattern.exec(offset);
}
return new Date(year, month, day);
},
refDate = (refDate == null || refDate === "" ? new Date() : refDate ),
newDate = (date == null || date === "" ?
defaultDate :
(typeof date === "string" ?
offsetString(date, refDate) :
(typeof date === "number" ?
(isNaN(date) ?
defaultDate :
offsetNumeric(date)
) :
new Date(date.getTime())
)
)
);
newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate);
if (newDate) {
newDate.setHours(0);
newDate.setMinutes(0);
newDate.setSeconds(0);
newDate.setMilliseconds(0);
}
return newDate;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment