Skip to content

Instantly share code, notes, and snippets.

@BeFiveINFO
Created September 13, 2015 13:49
Show Gist options
  • Save BeFiveINFO/b80c0bc5078107332906 to your computer and use it in GitHub Desktop.
Save BeFiveINFO/b80c0bc5078107332906 to your computer and use it in GitHub Desktop.
Javascript time conversion functions
/*
* Calculates the Twitter time since the tweet was created
* Based on http://www.jquery4u.com/api-calls/calculate-twitter-time-tweet-javascript/
* @param obj with datetime (e.g. git time etc). and limitSwitch (optional) in minute --- any dates beyond that will be in date in string
* @return time since in html
*/
var calculateSince = function ( _parameter ) {
var _datetime = _parameter.dateTime.replace(/\-/g,'/');
var _limitSwitch = (_parameter.limitSwitch) ? _parameter.limitSwitch : 4320; /* optional */
var _tTime = new Date(_datetime);
var _cTime = new Date();
var _sinceMin = Math.round((_cTime - _tTime) / 60000);
var _since = '';
var _sinceHr = 0;
var _sinceDay = 0;
var _sinceSec = 0;
switch (true) {
case _sinceMin === 0 :
_sinceSec = Math.round((_cTime - _tTime) / 1000);
if (_sinceSec < 10) {
_since = 'less than 10 seconds ago';
} else {
_since = _sinceSec +' seconds ago';
}
break;
case _sinceMin === 1 :
_sinceSec = Math.round((_cTime - _tTime) / 1000);
if (_sinceSec == 30) {
_since = 'half a minute ago';
} else if (_sinceSec < 60) {
_since = 'less than a minute ago';
} else {
_since = '1 minute ago';
}
break;
case _sinceMin < 45 :
_since = _sinceMin + ' minutes ago';
break;
case _sinceMin > 44 && _sinceMin < 60 :
_since = 'about 1 hour ago';
break;
case _sinceMin < 1440 :
_sinceHr = Math.round(_sinceMin / 60);
if (_sinceHr == 1) {
_since = 'about 1 hour ago';
} else {
_since = 'about ' + _sinceHr + ' hours ago';
}
break;
case _sinceMin > 1439 && _sinceMin < 2879 :
_since = '1 day ago';
break;
case _sinceMin > 2880 && _sinceMin < _limitSwitch :
_sinceDay = Math.round(_sinceMin / 1440);
_since = _sinceDay + ' days ago';
break;
default :
_since = _datetime;
break;
}
return _since;
};
/*
* Converts unixtime stamp (you need to make sure that the time stamp is UTC) to UTC Date in string.
* reference : http://d.hatena.ne.jp/yutakikuchi/20111015/1318633937
* @param unixtime stamp
* @return UTC Date in string.
*/
var convertUnixTimestampToDateTime = function (_unixTimestamp ) {
return _dateUTCString = new Date( _unixTimestamp * 1000 ).toUTCString();
};
/*
* Converts time in string to unix timestamp
* reference : http://d.hatena.ne.jp/yutakikuchi/20111015/1318633937
* @param time in string
* @return UTC Date in string.
*/
var convertDateTimeToUnixTimestamp = function ( _dateTime ) {
return Date.parse( _dateTime.replace( /-/g, '/') ) / 1000;
};
/*
todo:
more conversion routines
php version of above ...
UTC <-> local time conversion
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment