takes '3 hours 10 minutes ago'
and convert to actual time
Created
September 14, 2017 11:28
-
-
Save brotich/2d33423dcb48187e296a489f817fe002 to your computer and use it in GitHub Desktop.
convert time ago time to local time using offset
This file contains 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
var timeStr = '3 hours 10 minutes ago'; | |
function splitTimeAgoString(timeString) { | |
var timeArray = timeStr.split(' '); | |
var timeDelta = timeArray.pop(); | |
if (timeArray.length % 2 !== 0) { | |
throw new Error('Time array unexpected: ' + JSON.stringify(timeArray)); | |
} | |
var timeValues = timeArray.reduce( function(result, value, index, array) { | |
if (index % 2 === 0) | |
result.push({ | |
value: array[index], | |
unit: array[index + 1], | |
}); | |
return result; | |
}, []); | |
return { | |
timeValues: timeValues, | |
timeDelta: timeDelta, | |
}; | |
} | |
function convertTimeAgoToSec(timeUnits) { | |
var timeValues = timeUnits.timeValues; | |
var timeDelta = timeUnits.timeDelta; | |
var seconds = timeValues.reduce( function(result, time) { | |
switch(time.unit) { | |
case 'days': | |
result += (time.value * 60 * 60 * 24); | |
break; | |
case 'hours': | |
result += (time.value * 60 * 60); | |
break; | |
case 'minutes': | |
result += (time.value * 60); | |
break; | |
case 'seconds': | |
result += time.value; | |
break; | |
default: | |
console.error('unknown time unit: ' + JSON.stringify(time, null, 2)); | |
result += 0; | |
} | |
return result; | |
}, 0); | |
return timeDelta === 'ago' ? -seconds : seconds; | |
} | |
function getCheckedTime(timeStr) { | |
try { | |
var timeUnits = splitTimeAgoString(timeStr); | |
var timeDiff = convertTimeAgoToSec(timeUnits); | |
var checkedDate = new Date(Date.now() + timeDiff * 1000); | |
return checkedDate.toString(); | |
} catch(e) { | |
console.error('ERROR: getCheckedTime' + e); | |
return timeStr; | |
} | |
} | |
console.log(getCheckedTime(timeStr)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment