Skip to content

Instantly share code, notes, and snippets.

@brotich
Created September 14, 2017 11:28
Show Gist options
  • Save brotich/2d33423dcb48187e296a489f817fe002 to your computer and use it in GitHub Desktop.
Save brotich/2d33423dcb48187e296a489f817fe002 to your computer and use it in GitHub Desktop.
convert time ago time to local time using offset

takes '3 hours 10 minutes ago' and convert to actual time

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