Created
August 25, 2015 19:29
-
-
Save dominikbulaj/6f950c79741edf429efb to your computer and use it in GitHub Desktop.
Add or remove time from given date. Examples:
getNewTime('7 days') // return current time + 7 days
getNewTime('-1 month') // return past time (last month)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Add (or remove) some time from current date. Returns new Date | |
* | |
* @param {string} elapsedTime | |
* @param {Date|null} dateObject | |
* @returns {Date} | |
* @private | |
*/ | |
function getNewTime(elapsedTime, dateObject) { | |
var newDate = new Date(); | |
// no dateObjecy | |
switch (typeof dateObject) { | |
case 'undefined': // no action - newDate already defined | |
break; | |
case 'number': | |
newDate = new Date(dateObject); | |
break; | |
case 'string': | |
newDate = new Date(dateObject); | |
break; | |
} | |
var elapsedTimeParts = elapsedTime.match(/^(\-?\s*\d+)\s+(hours?|days?|months?)$/); | |
if (elapsedTimeParts) { // must be valid format | |
var timeDiff = parseInt(elapsedTimeParts[1].replace(/\s+/, ''), 10); | |
switch (elapsedTimeParts[2]) { | |
case 'hour': | |
case 'hours': | |
newDate.setHours(newDate.getHours() + timeDiff); | |
break; | |
case 'days': | |
case 'day': | |
newDate.setDate(newDate.getDate() + timeDiff); | |
break; | |
case 'month': | |
case 'months': | |
newDate.setMonth(newDate.getMonth() + timeDiff); | |
break; | |
} | |
} | |
return newDate; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment