I am trying to display facebook newsfeed and displaying them on mobile web app. It is working fine but the problem is that it does not display time in timeago format(i.e. 2 days ago) on mobile web browser, on the other hand it does display properly on desktop. The format of the date and time is 2011-09-13T11:28:19+0000.
on mobile it displays NaN years ago.
here is my code for timeago function
timeAgo('2011-09-13T11:28:19+0000');
function timeAgo(date_time) {
//to get unix timestamp
var currentDate = Math.round(+new Date()/1000);
var tweetDate = Math.round(+new Date(date_time)/1000);
//alert(tweetDate);
var diffTime = currentDate - tweetDate;
//alert(diffTime);
if (diffTime < 59) return 'less than a minute ago';
else if(diffTime > 59 && diffTime < 120) return 'about a minute ago';
else if(diffTime >= 121 && diffTime <= 3600) return (parseInt(diffTime / 60)).toString() + ' minutes ago';
else if(diffTime > 3600 && diffTime < 7200) return '1 hour ago';
else if(diffTime > 7200 && diffTime < 86400) return (parseInt(diffTime / 3600)).toString() + ' hours ago';
else if(diffTime > 86400 && diffTime < 172800) return '1 day ago';
else if(diffTime > 172800 && diffTime < 604800) return (parseInt(diffTime / 86400)).toString() + ' days ago';
else if(diffTime > 604800 && diffTime < 12089600) return '1 week ago';
else if(diffTime > 12089600 && diffTime < 2630880) return (parseInt(diffTime / 604800)).toString() + ' weeks ago';
else if(diffTime > 2630880 && diffTime < 5261760) return '1 month ago';
else if(diffTime > 5261760 && diffTime < 31570560) return (parseInt(diffTime / 2630880)).toString() + ' months ago';
else if(diffTime > 31570560 && diffTime < 63141120) return '1 year ago';
else return (parseInt(diffTime / 31570560)).toString() + ' years ago';
}
How can I solve this problem?
I had a similar problem and i fixed it using the following function.
function relative_time(date_str) {
if (!date_str) {return;}
date_str = $.trim(date_str);
date_str = date_str.replace(/\.\d\d\d+/,""); // remove the milliseconds
date_str = date_str.replace(/-/,"/").replace(/-/,"/"); //substitute - with /
date_str = date_str.replace(/T/," ").replace(/Z/," UTC"); //remove T and substitute Z with UTC
date_str = date_str.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); // +08:00 -> +0800
var parsed_date = new Date(date_str);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date(); //defines relative to what ..default is now
var delta = parseInt((relative_to.getTime()-parsed_date)/1000);
delta=(delta<2)?2:delta;
var r = '';
if (delta < 60) {
r = delta + ' seconds ago';
} else if(delta < 120) {
r = 'a minute ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60, 10)).toString() + ' minutes ago';
} else if(delta < (2*60*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600, 10)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = 'a day ago';
} else {
r = (parseInt(delta / 86400, 10)).toString() + ' days ago';
}
return 'about ' + r;
};
this will help you alot:
someone already did it for you in a jquery plugin
http://timeago.yarp.com/
Related
Is you'll probably be able to tell I'm a complete JS rookie but I've spent my day working on this code to display a shipping timer, compiled from bits of various other posts on SO (thanks!).
It seemed to be going well until I completed adding all the functionality I needed and now it's not working. When you first run the snippet it works correctly but as soon as it ticks the "day" value displays incorrectly (it should display 'tomorrow' but it switches to 'today') and the timer itself has stopped counting down.
I can't figure out for the life of me where I messed it up so looking for some assistance if possible! Thanks in advance.
JSFiddle: http://jsfiddle.net/c3otusv6/
(function() {
var start = new Date();
start.setHours(14, 0, 0);
var maybePluralize = function maybePluralize(count, noun) {
var suffix = arguments.length <= 2 || arguments[2] === undefined ? 's' : arguments[2];
return count + ' ' + noun + (count !== 1 ? suffix : '');
};
var now = new Date();
var day = now.getDay();
function tick() {
if (day >= 1 && day <= 5 && now < start) {
document.getElementById('ddate').innerHTML = 'today';
} else if (day >= 1 && day <= 4 && now >= start || day == 7) {
document.getElementById('ddate').innerHTML = 'tomorrow';
} else if (day == 5 && now >= start || day == 6) {
document.getElementById('ddate').innerHTML = 'Monday';
}
if (day == 6 || day == 5 && now > start || day == 7 && now < start) {
document.getElementById('countdown').innerHTML = "now";
} else {
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = (start - now) / 1000;
var hh = Math.floor(remain / 60 / 60 % 60);
var mm = Math.floor(remain / 60 % 60);
document.getElementById('countdown').innerHTML = "in the next <strong>" + maybePluralize(hh, 'hour') + " " + maybePluralize(mm, 'min') + "</strong>";
setTimeout(tick, 1000);
}
}
document.addEventListener('DOMContentLoaded', tick);
})();
If you need to have the function called every second, you need to use setInterval. setTimeout just runs the given function once after the specified number of seconds.
I have made small edit to you fiddle, to make it run every second.
As for the "day" value being incorrect, I think you need to check your if statements. I quite dont understand your business logic.
Also note - Sunday is given by '0' in getDay. And I see you using day == 7, so you might want to check that and do the necessary adjustments. I guess you need to -1 from all your if statements for day.
http://jsfiddle.net/wm9kj8yb/
(function() {
var start = new Date();
var now = new Date();
var day = now.getDay();
start.setHours(14, 0, 0);
function maybePluralize(count, noun) {
var suffix = arguments.length <= 2 || arguments[2] === undefined ? 's' : arguments[2];
return count + ' ' + noun + (count !== 1 ? suffix : '');
};
function tick() {
now = new Date();
day = now.getDay();
if (day >= 1 && day <= 5 && now < start) {
document.getElementById('ddate').innerHTML = 'today';
} else if (day >= 1 && day <= 4 && now >= start || day == 7) {
document.getElementById('ddate').innerHTML = 'tomorrow';
} else if (day == 5 && now >= start || day == 6) {
document.getElementById('ddate').innerHTML = 'Monday';
}
if (day == 6 || day == 5 && now > start || day == 7 && now < start) {
document.getElementById('countdown').innerHTML = "now";
} else {
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = (start - now) / 1000;
var ss = Math.floor(remain % 60);
remain = Math.floor(remain / 60);
var mm = remain % 60;
remain = Math.floor(remain / 60);
var hh = remain % 60;
document.getElementById('countdown').innerHTML = "in the next <strong>" + maybePluralize(hh, 'hour') + " " + maybePluralize(mm, 'min') + " " + " " + maybePluralize(ss, 'sec') + "</strong>";
}
}
document.addEventListener('DOMContentLoaded', function() {
setInterval(tick, 1000);
});
})();
Order <span id='countdown'></span> for dispatch <span id='ddate'></span>
Current code that I have is this, but it is not returning individual values:
I want to make days, hours and minutes individual values to use with another javascript codes..
function convertToDaysHoursMins(time, allowzero = false)
{
if (!allowzero && (time === 0 || time < 1))
return 'unlimited';
else if(allowzero && (time === 0 || time < 1))
return '0m';
let format = '';
days = Math.floor(time / 1440);
if(days > 0) format = format + days + 'd ';
hours = Math.floor(time / 60);
if(hours > 0 && (hours % 24) != 0) format = format + (hours - (days * 24)) + 'h '
format
minutes = (time % 60);
if(minutes > 0) format = format + minutes + 'm';
return [days, hours, minutes];
}
Try this:
function convertToDaysHoursMins(time, allowzero = false)
{
if (!allowzero && (time === 0 || time < 1))
return 'unlimited';
else if(allowzero && (time === 0 || time < 1))
return '0m';
let format = '';
days = Math.floor(time / 1440);
if(days > 0) format = format + days + 'd ';
hours = Math.floor(time / 60);
if(hours > 0 && (hours % 24) != 0) format = format + (hours - (days * 24)) + 'h '
format
minutes = (time % 60);
if(minutes > 0) format = format + minutes + 'm';
if(format !== '')
return format
else
return '-';
}
console.log(convertToDaysHoursMins(4556))
Try this:
function convertToDaysHoursMins(time, allowzero = false)
{
if (!allowzero && (time === 0 || time < 1))
return 'unlimited';
else if(allowzero && (time === 0 || time < 1))
return [0,0,0];
days = Math.floor(time / 1440);
hours = Math.floor(time / 60);
if(hours > 0 && (hours % 24) != 0) hours = hours - (days * 24)
minutes = (time % 60);
return [days, hours, minutes];
}
const result = convertToDaysHoursMins(4556);
console.log(result[0]);
console.log(result[1]);
console.log(result[2]);
change elgg_get_friendly_time to javascript
I strucked in this $params = array('time' => $time); and return elgg_echo("friendlytime:justnow");
<?php
function elgg_get_friendly_time($time) {
// return a time string to short circuit normal time formatting
$params = array('time' => $time);
$result = elgg_trigger_plugin_hook('format', 'friendly:time', $params, NULL);
if ($result) {
return $result;
}
$diff = time() - (int)$time;
$minute = 60;
$hour = $minute * 60;
$day = $hour * 24;
if ($diff < $minute) {
return elgg_echo("friendlytime:justnow");
} else if ($diff < $hour) {
$diff = round($diff / $minute);
if ($diff == 0) {
$diff = 1;
}
if ($diff > 1) {
return elgg_echo("friendlytime:minutes", array($diff));
} else {
return elgg_echo("friendlytime:minutes:singular", array($diff));
}
} else if ($diff < $day) {
$diff = round($diff / $hour);
if ($diff == 0) {
$diff = 1;
}
if ($diff > 1) {
return elgg_echo("friendlytime:hours", array($diff));
} else {
return elgg_echo("friendlytime:hours:singular", array($diff));
}
} else {
$diff = round($diff / $day);
if ($diff == 0) {
$diff = 1;
}
if ($diff > 1) {
return elgg_echo("friendlytime:days", array(diff));
} else {
return elgg_echo("friendlytime:days:singular", array($diff));
}
}
}
?>
I looked up the docs for the function:
http://reference.elgg.org/engine_2lib_2output_8php.html#aa008ab7b454c680f83ca7a62409c6ab5
and it reminded me I have some JS code that does something similar, which might help you:
function get_friendly_date(date) {
var now = new Date();
var diff = Math.floor((now - date) / 1000); // seconds
var min = 60; // seconds
var hour = 3600; // seconds
var day = 86400; // seconds
var month = 30.5 * day; // seconds
months = Math.floor(diff / month);
if (months >= 1) return months + " months ago";
else {
days = Math.floor(diff / day);
if (days == 1) return days + " day ago";
else if (days > 1) return days + " days ago";
else {
hours = Math.floor(diff / hour);
if (hours == 1) return hours + " hour ago"
else if (hours > 1) return hours + " hours ago";
else {
mins = Math.floor(diff / min);
if (mins == 1) return mins + " min ago";
else if (mins > 1) return mins + " mins ago";
else {
return diff + " seconds ago";
}
}
}
}
}
which I put in a fiddle, that you can play around with here:
http://jsfiddle.net/hM2LU/
Hope that helps!
I have a date field in mysql that has datetime in the below period :
2014-05-31 15:00:55
I want to convert this value to "passed time" till current time.
for example if two hours are passed till the saved time,then I want something like this :
two hours ago
if three days are passed till the saved time,then it should be:
three days ago
I am trying to display the output with php as following :
<?php
echo '<p align="right">';
echo $row2['date'] ;
echo '</p>';
?>
I am new in PHP,Can anyone help me out.
You could try something like this:
function timeDiff(current, previous) {
var msPerMin = 60 * 1000;
var msPerHr = msPerMin * 60;
var msPerDay = msPerHr * 24;
var msPerMonth = msPerDay * 30;
var msPerYear = msPerDay * 365;
var elapsed = current - previous;
if (elapsed < msPerMin) {
return Math.round(elapsed / 1000) + ' seconds ago';
}
else if (elapsed < msPerHr) {
return Math.round(elapsed / msPerMin) + ' minutes ago';
}
else if (elapsed < msPerDay ) {
return Math.round(elapsed / msPerHr ) + ' hours ago';
}
else if (elapsed < msPerMonth) {
return 'approximately ' + Math.round(elapsed / msPerDay) + ' days ago';
}
else if (elapsed < msPerYear) {
return 'approximately ' + Math.round(elapsed / msPerMonth) + ' months ago';
}
else {
return 'approximately ' + Math.round(elapsed / msPerYear ) + ' years ago';
}
}
Source: Javascript timestamp to relative time (eg 2 seconds ago, one week ago etc), best methods?
This is how you implement it:
var now = new Date();
var someDate = new Date(2011, 04, 24, 12, 30, 00, 00);
alert(timeDiff(now, someDate));
Fiddle.
I've a requirement where I want to convert milliseconds to xHours and yMins in AngularJS.
For ex. 3600000 should be displayed as 1h 0m.
I tried using date:'H:m' and date:'HH:mm' from the date formats on Angular's website.
But those give 19:0 and 19:00 instead of 1h 0m.
Any pointers of achieving this will be helpful.
Thanks
Let make a custom filter for this, e.g:
.filter('millSecondsToTimeString', function() {
return function(millseconds) {
var oneSecond = 1000;
var oneMinute = oneSecond * 60;
var oneHour = oneMinute * 60;
var oneDay = oneHour * 24;
var seconds = Math.floor((millseconds % oneMinute) / oneSecond);
var minutes = Math.floor((millseconds % oneHour) / oneMinute);
var hours = Math.floor((millseconds % oneDay) / oneHour);
var days = Math.floor(millseconds / oneDay);
var timeString = '';
if (days !== 0) {
timeString += (days !== 1) ? (days + ' days ') : (days + ' day ');
}
if (hours !== 0) {
timeString += (hours !== 1) ? (hours + ' hours ') : (hours + ' hour ');
}
if (minutes !== 0) {
timeString += (minutes !== 1) ? (minutes + ' minutes ') : (minutes + ' minute ');
}
if (seconds !== 0 || millseconds < 1000) {
timeString += (seconds !== 1) ? (seconds + ' seconds ') : (seconds + ' second ');
}
return timeString;
};
});
Then use it:
<div>{{ millSeconds | millSecondsToTimeString }}</div>
There is date converter in AngularJS, just set required date format:
{{milliseconds | date:'yyyy-MM-dd HH:mm'}}
Also I created such 'timeAgo' filter using jQuery timeago() function:
.filter('timeAgo', function() {
return function(input) {
if (input == null) return "";
return jQuery.timeago(input);
};
})
Usage:
{{milliseconds | timeAgo}}
or use together both format for wide date representation:
<span>{{milliseconds | timeAgo}}, {{milliseconds | date:'yyyy-MM-dd HH:mm'}}</span>
Result:
12 minutes ago, 2015-03-04 11:38
You'll want to use moment's duration objects.
To do what you want, try this:
app.controller 'MainCtrl', ($scope) ->
$scope.name = 'World'
$scope.milliseconds = 3600000
$scope.duration = moment.duration($scope.milliseconds)
And the markup
<body ng-controller="MainCtrl">
<p>Milliseconds: {{milliseconds}}</p>
<p>Duration: {{duration.hours()}}h {{duration.minutes()}}m</p>
</body>
plunkr: http://plnkr.co/edit/2HL75Tmr4CoAy5R9smkx
Thanks. I've modified your filter slightly to return duration in hh:mm:ss format.
.filter('duration', function() {
//Returns duration from milliseconds in hh:mm:ss format.
return function(millseconds) {
var seconds = Math.floor(millseconds / 1000);
var h = 3600;
var m = 60;
var hours = Math.floor(seconds/h);
var minutes = Math.floor( (seconds % h)/m );
var scnds = Math.floor( (seconds % m) );
var timeString = '';
if(scnds < 10) scnds = "0"+scnds;
if(hours < 10) hours = "0"+hours;
if(minutes < 10) minutes = "0"+minutes;
timeString = hours +":"+ minutes +":"+scnds;
return timeString;
}
});
For anyone who wants to have comma separators (e.g. '21 days, 14 hours, 7 minutes'):
'use strict';
angular.module('contests').filter('duration', function () {
return function(milliseconds) {
var seconds = Math.floor(milliseconds / 1000);
var days = Math.floor(seconds / 86400);
var hours = Math.floor((seconds % 86400) / 3600);
var minutes = Math.floor(((seconds % 86400) % 3600) / 60);
var dateTimeDurationString = '';
if ((days > 0) && (hours === 0 && minutes === 0)) dateTimeDurationString += (days > 1) ? (days + ' days ') : (days + ' day ');
if ((days > 0) && (hours > 0 || minutes > 0)) dateTimeDurationString += (days > 1) ? (days + ' days, ') : (days + ' day, ');
if ((hours > 0) && (minutes > 0)) dateTimeDurationString += (hours > 1) ? (hours + ' hours, ') : (hours + ' hour, ');
if ((hours > 0) && (minutes === 0)) dateTimeDurationString += (hours > 1) ? (hours + ' hours ') : (hours + ' hour ');
if (minutes > 0) dateTimeDurationString += (minutes > 1) ? (minutes + ' minutes ') : (minutes + ' minute ');
return dateTimeDurationString;
};
});
Try this one
var app = angular.module ( 'myApp', [] ) ;
app.controller ( 'myController', function ( $scope, $filter) {
$scope.date = $filter('date')(milliseconds, 'MM/dd/yyyy');
});
Use below syntax
$filter('date')(dateObj, format)
e.g.
$filter('date')(1324339200000, 'dd/MM/yyyy');
(function () {
'use strict';
angular
.module('module_name')
.filter('secondsToDateTime', secondsToDateTime);
function secondsToDateTime() {
return function(seconds) {
return new Date(1970, 0, 1).setSeconds(seconds);
};
}
})();
<span>{{seconds | secondsToDateTime | date:'HH:mm:ss'}}</span>
For TypeScript but could be adapted for any language.
convertTimeMS(timeMS: number): string {
const seconds = Math.floor(timeMS / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
let str: string = '';
if(hours > 0) {
str = str + hours.toString() + 'h ';
}
if(minutes%60 > 0) {
str = str + Number(minutes%60).toString() + 'm ';
}
if(seconds%60 > 0) {
str = str + Number(seconds%60).toString() + 's ';
}
return str;
}