change elgg php function to javascript function - javascript

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!

Related

Return DaysHoursMins with individual returns

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]);

Need help resetting a javascript countdown timer

So I am a web designer and I inherited a site from another developer. The site in question is for an annual event and features a countdown timer on the home page. I am still pretty new to js and could use some help resetting the timer to next years date of March 1st, 2019. I have posted the code for the count down timer below. Any advice would be much appreciated!
(function($) {
$.fn.countdown = function(options, callback) {
//custom 'this' selector
thisEl = $(this);
//array of custom settings
var settings = {
'date': null,
'format': null
};
//append the settings array to options
if(options) {
$.extend(settings, options);
}
//main countdown function
function countdown_proc() {
eventDate = Date.parse(settings['date']) / 1000;
currentDate = Math.floor($.now() / 1000);
if(eventDate <= currentDate) {
callback.call(this);
clearInterval(interval);
}
seconds = eventDate - currentDate;
days = Math.floor(seconds / (60 * 60 * 24)); //calculate the number of days
seconds -= days * 60 * 60 * 24; //update the seconds variable with no. of days removed
hours = Math.floor(seconds / (60 * 60));
seconds -= hours * 60 * 60; //update the seconds variable with no. of hours removed
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60; //update the seconds variable with no. of minutes removed
//conditional Ss
if (days == 1) { thisEl.find(".timeRefDays").text("day"); } else { thisEl.find(".timeRefDays").text("days"); }
if (hours == 1) { thisEl.find(".timeRefHours").text("hour"); } else { thisEl.find(".timeRefHours").text("hours"); }
if (minutes == 1) { thisEl.find(".timeRefMinutes").text("minute"); } else { thisEl.find(".timeRefMinutes").text("minutes"); }
if (seconds == 1) { thisEl.find(".timeRefSeconds").text("second"); } else { thisEl.find(".timeRefSeconds").text("seconds"); }
//logic for the two_digits ON setting
if(settings['format'] == "on") {
days = (String(days).length >= 2) ? days : "0" + days;
hours = (String(hours).length >= 2) ? hours : "0" + hours;
minutes = (String(minutes).length >= 2) ? minutes : "0" + minutes;
seconds = (String(seconds).length >= 2) ? seconds : "0" + seconds;
}
//update the countdown's html values.
if(!isNaN(eventDate)) {
thisEl.find(".days").text(days);
thisEl.find(".hours").text(hours);
thisEl.find(".minutes").text(minutes);
thisEl.find(".seconds").text(seconds);
} else {
alert("Invalid date. Here's an example: 12 Tuesday 2012 17:30:00");
clearInterval(interval);
}
}
//run the function
countdown_proc();
//loop the function
interval = setInterval(countdown_proc, 1000);
}
}) (jQuery);
You need to construct a date via the Date object and then pass the date and a callback function to countdown
const oneHourFromNow= new Date();
oneHourFromNow.setHours(oneHourFromNow.getHours() + 1);
const config = {
"date": oneHourFromNow.toString(),
"format": "off"
}
const callbackFunc = function() {console.log("Do something");}
$.fn.countdown(config , callbackFunc );
(function($) {
let interval;
$.fn.countdown = function(options, callback) {
//custom 'this' selector
// I hard-coded this ***
thisEl = $('#countdown-timer');
//array of custom settings
var settings = {
'date': null,
'format': null
};
//append the settings array to options
if(options) {
$.extend(settings, options);
}
//main countdown function
function countdown_proc() {
eventDate = Date.parse(settings['date']) / 1000;
currentDate = Math.floor($.now() / 1000);
if(eventDate <= currentDate) {
callback.call(this);
clearInterval(interval);
}
seconds = eventDate - currentDate;
days = Math.floor(seconds / (60 * 60 * 24)); //calculate the number of days
seconds -= days * 60 * 60 * 24; //update the seconds variable with no. of days removed
hours = Math.floor(seconds / (60 * 60));
seconds -= hours * 60 * 60; //update the seconds variable with no. of hours removed
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60; //update the seconds variable with no. of minutes removed
//console.log(thisEl, thisEl.find(".timeRefDays"));
//conditional Ss
if (days == 1) { thisEl.find(".timeRefDays").text("day"); } else { thisEl.find(".timeRefDays").text("days"); }
if (hours == 1) { thisEl.find(".timeRefHours").text("hour"); } else { thisEl.find(".timeRefHours").text("hours"); }
if (minutes == 1) { thisEl.find(".timeRefMinutes").text("minute"); } else { thisEl.find(".timeRefMinutes").text("minutes"); }
if (seconds == 1) { thisEl.find(".timeRefSeconds").text("second"); } else { thisEl.find(".timeRefSeconds").text("seconds"); }
//logic for the two_digits ON setting
if(settings['format'] == "on") {
days = (String(days).length >= 2) ? days : "0" + days;
hours = (String(hours).length >= 2) ? hours : "0" + hours;
minutes = (String(minutes).length >= 2) ? minutes : "0" + minutes;
seconds = (String(seconds).length >= 2) ? seconds : "0" + seconds;
}
//update the countdown's html values.
if(!isNaN(eventDate)) {
thisEl.find(".days").text(days);
thisEl.find(".hours").text(hours);
thisEl.find(".minutes").text(minutes);
thisEl.find(".seconds").text(seconds);
} else {
alert("Invalid date. Here's an example: 12 Tuesday 2012 17:30:00");
clearInterval(interval);
}
}
//run the function
countdown_proc();
//loop the function
interval = setInterval(countdown_proc, 1000);
}
// here you can create your Date instance any way you like:
const oneHourFromNow= new Date();
oneHourFromNow.setHours(oneHourFromNow.getHours() + 1);
const config = {
"date": oneHourFromNow.toString(),
"format": "off"
}
const callbackFunc = function() {console.log("Do something");}
$.fn.countdown(config , callbackFunc );
}) (jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="countdown-timer">
<span class="days"></span> <span class="timeRefDays"></span>
<span class="hours"></span> <span class="timeRefHours"></span>
<span class="minutes"></span> <span class="timeRefMinutes"></span>
<span class="seconds"></span> <span class="timeRefSeconds"></span>
</div>

use host date in javascript counter

I am using this script for countdown in my site and it's work
<script type="text/javascript">
(function (e) {
e.fn.countdown = function (t, n) {
function i() {
eventDate = Date.parse(r.date) / 1e3;
currentDate = Math.floor(e.now() / 1e3);
if (eventDate <= currentDate) {
n.call(this);
clearInterval(interval)
}
seconds = eventDate - currentDate;
days = Math.floor(seconds / 86400);
seconds -= days * 60 * 60 * 24;
hours = Math.floor(seconds / 3600);
seconds -= hours * 60 * 60;
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
days == 1 ? thisEl.find(".timeRefDays").text("day") : thisEl.find(".timeRefDays").text("day");
hours == 1 ? thisEl.find(".timeRefHours").text("hours") : thisEl.find(".timeRefHours").text("hours");
minutes == 1 ? thisEl.find(".timeRefMinutes").text("Minutes") : thisEl.find(".timeRefMinutes").text("Minutes");
seconds == 1 ? thisEl.find(".timeRefSeconds").text("Seconds") : thisEl.find(".timeRefSeconds").text("Seconds");
if (r["format"] == "on") {
days = String(days).length >= 2 ? days : "0" + days;
hours = String(hours).length >= 2 ? hours : "0" + hours;
minutes = String(minutes).length >= 2 ? minutes : "0" + minutes;
seconds = String(seconds).length >= 2 ? seconds : "0" + seconds
}
if (!isNaN(eventDate)) {
thisEl.find(".days").text(days);
thisEl.find(".hours").text(hours);
thisEl.find(".minutes").text(minutes);
thisEl.find(".seconds").text(seconds)
} else {
alert("Invalid date. Example: 30 Tuesday 2013 15:50:00");
clearInterval(interval)
}
}
thisEl = e(this);
var r = {
date: null,
format: null
};
t && e.extend(r, t);
i();
interval = setInterval(i, 1e3)
}
})(jQuery);
$(document).ready(function () {
function e() {
var e = new Date;
e.setDate(e.getDate() + 60);
dd = e.getDate();
mm = e.getMonth() + 1;
y = e.getFullYear();
futureFormattedDate = mm + "/" + dd + "/" + y;
return futureFormattedDate
}
$("#countdown").countdown({
date: "<?php echo $newcounter ?> ", // Change this to your desired date to countdown to
format: "on"
});
});
</script>
but i have a problem. this script use my user computer date but i want use my site host date. how can change my date read from my host?
thank you.
Pretty sure this will work:
currentDate = <?php echo time() ?>;
Looks like currentDate is just a Unix timestamp which time() will provide for you.

AngularJS - How do you convert milliseconds to xHours and yMins

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;
}

how to convert date and time to timeago format in jquery

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/

Categories

Resources