Created
October 7, 2017 00:16
-
-
Save mhou1981/88eb87168b83e5e7b90b7f9bcf25ae84 to your computer and use it in GitHub Desktop.
JavaScript date function allow to input time difference from now.
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
function myDate(description) { | |
var result = new Date(); | |
if (description === undefined || description == "" || description.trim() == "") { | |
console.info(description + "=[" + result + "]"); | |
return result; | |
} | |
var desc = description.trim().toLowerCase(); | |
var section = desc.split(" "); | |
if (section.length < 2) { | |
console.info(description + "=[" + result + "]"); | |
return result; | |
} | |
var temp = 0; | |
for (var i = 0; i < section.length; i++) { | |
var word = section[i]; | |
if (!isNaN(word)) { | |
temp = parseInt(word); | |
} else { | |
if (section[section.length - 1] == "ago") { | |
temp *= -1; | |
} | |
switch (word) { | |
case 'second': | |
case 'seconds': | |
result.setSeconds(result.getSeconds() + temp); | |
break; | |
case 'minute': | |
case 'minutes': | |
result.setMinutes(result.getMinutes() + temp); | |
break; | |
case 'hour': | |
case 'hours': | |
result.setHours(result.getHours() + temp); | |
break; | |
case 'day': | |
case 'days': | |
result.setDate(result.getDate() + temp); | |
break; | |
case 'month': | |
case 'months': | |
result.setMonth(result.getMonth() + temp); | |
break; | |
case 'year': | |
case 'years': | |
result.setFullYear(result.getFullYear() + temp); | |
break; | |
default: | |
break; | |
} | |
temp = 0; | |
} | |
} | |
console.info(description + "=[" + result + "]"); | |
return result; | |
} | |
var time = myDate(); | |
time = myDate("2 years 13 month ago"); | |
time = myDate("1 years 1 month ago"); | |
time = myDate("1 years 1 month 1 day 1 hour 1 minute 1 second ago"); | |
time = myDate("in 2 years 13 month"); | |
time = myDate("in 1 years 1 month"); | |
time = myDate("in 1 years 1 month 1 day 1 hour 1 minute 1 second"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment