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.
Related
I'm new in javascript.
My PHP script returns a value in this format
d:h:m:s
Now I would like to have a countdown which is able to countdown each second from this.
I modified a countdown. This works once a time, after the countdown "ticks" each second it returns NaN all the time. Any idea what I do wrong?
$(document).ready(function() {
setInterval(function() {
$('.countdown').each(function() {
var time = $(this).data("time").split(':');
var timestamp = time[0] * 86400 + time[1] * 3600 + time[2] * 60 + time[3] * 1;
var days = Math.floor(timestamp / 86400);
console.log(time,timestamp);
var hours = Math.floor((timestamp - days * 86400) / 3600);
var minutes = Math.floor((timestamp - hours * 3600) / 60);
var seconds = timestamp - ((days * 86400) + (hours * 3600) + (minutes * 60))-1;
$(this).data("time",""+days+":"+hours+":"+minutes+":"+seconds);
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
$(this).text(days + ':' + hours + ':' + minutes + ':' + seconds);
});
}, 1000);
})
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown">02:03:05:59</h1>
As far as I can see you have 2 problems here:
after the first execution you change the pattern of the text you display in the h1. First you have 02:03:05:59. Then you want to write 02 days 03:05:58 into the tag. Next time you parse it, you get the error because you split at : and that does not work anymore as you have days instead of : as the seperator for the first part.
When calculating the minutes, you should also substract the days and not just the hours.
When you wan to keep the dd:hh:mm:ss format, you could do it like this:
$(document).ready(function() {
setInterval(function() {
$('.countdown').each(function() {
var time = $(this).text().split(':');
var timestamp = time[0] * 86400 + time[1] * 3600 + time[2] * 60 + time[3] * 1;
timestamp -= timestamp > 0;
var days = Math.floor(timestamp / 86400);
console.log(days);
var hours = Math.floor((timestamp - days * 86400) / 3600);
var minutes = Math.floor((timestamp - days * 86400 - hours * 3600) / 60);
var seconds = timestamp - days * 86400 - hours * 3600 - minutes * 60;
if (days < 10) {
days = '0' + days;
}
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
$(this).text(days + ':' + hours + ':' + minutes + ':' + seconds);
});
}, 1000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown">02:03:05:59</h1>
Your snippet goes from dd:hh:mm:ss to dd days, hh hours. So second time around, your tag contains non-parsable text.
I have changed it to something more precise. Something even MORE precise would be to give a timestamp in milliseconds in the future instead of something with seconds since it will take several seconds to render the page. If you round on minutes from the server, it would likely be better.
var aDay = 24*60*60*1000, anHour = 60*60*1000, aMin = 60*1000, aSec = 1000;
$(document).ready(function() {
$('.countdown').each(function() {
var time = $(this).data("time").split(':');
var date = new Date();
date.setDate(date.getDate()+parseInt(time[0],10))
date.setHours(date.getHours()+parseInt(time[1],10),date.getMinutes()+parseInt(time[2],10),date.getSeconds()+parseInt(time[3],10),0)
$(this).data("when",date.getTime());
});
setInterval(function() {
$('.countdown').each(function() {
var diff = new Date(+$(this).data("when"))-new Date().getTime();
var seconds, minutes, hours, days, x = diff / 1000;
seconds = Math.floor(x%60); x=(x/60|0); minutes = x % 60; x= (x/60|0); hours = x % 24; x=(x/24|0); days = x;
$(this).text(
days + ' day' +(days==1?", ":"s, ") +
hours + ' hour' +(hours==1?", ":"s, ") +
minutes + ' minute'+(minutes==1?", ":"s, ") +
seconds + ' second'+(seconds==1?".":"s.")
);
});
}, 500);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown" data-time="02:03:05:59"></h1>
I'm trying to learn a little more about JavaScript and decided to make a countdown timer that will show from years all the way down to milliseconds. It's just a learning experiment for me.
The minutes are not correct. If I refresh the browser, the seconds and minutes always start at 59. I think this may be because I am calling the Date object and possibly resetting it. What I am looking for is to count down to a certain date.
Because this is a learning experiment for me, if you see something else that may be improved upon, please let me know.
var dateA = new Date();
var dateB = new Date('June 3, 2014 00:27:00');
var cntr = setInterval(clock, 10);
function clock()
{
dateB = (dateB - 10);
var date = new Date(dateB);
var yrs = Math.abs(date.getUTCFullYear() - dateA.getUTCFullYear() );
var mos = Math.abs(date.getUTCMonth() - dateA.getUTCMonth());
var days = Math.abs(date.getUTCDate() - dateA.getUTCDate());
var hrs = Math.abs(date.getUTCHours() - dateA.getUTCHours());
var mins = Math.abs(date.getUTCMinutes() - dateA.getUTCMinutes());
var secs = Math.ceil(date.getUTCSeconds() - dateA.getUTCSeconds() / 60);
var mill = Math.ceil(date.getUTCMilliseconds() - dateA.getUTCMilliseconds() / 999);
var str =
yrs + ' Years ' +
mos + ' Months ' +
days + ' Days ' +
hrs + ' Hours ' +
mins + ' Mins ' +
secs + ' Secs ' +
mill + ' Mill';
document.getElementById('clock').innerHTML = str;
}
var yrs = Math.abs(date.getUTCFullYear() - dateA.getUTCFullYear() );
var mos = Math.abs(date.getUTCMonth() - dateA.getUTCMonth());
var days = Math.abs(date.getUTCDate() - dateA.getUTCDate());
var hrs = Math.abs(date.getUTCHours() - dateA.getUTCHours());
var mins = Math.abs(date.getUTCMinutes() - dateA.getUTCMinutes());
You cannot just take the absolute value of the differences of each part of the date! You end up with totally wrong numbers.
var secs = Math.ceil(date.getUTCSeconds() - dateA.getUTCSeconds() / 60);
var mill = Math.ceil(date.getUTCMilliseconds() - dateA.getUTCMilliseconds() / 999);
Why would you divide these by 60 and by nearly-1000?!
Instead, to calculate the time difference, you will need to get the complete difference (in milliseconds, usually) and convert that into the different units. Your function should look like this:
var el = document.getElementById('clock');
function clock() {
var diff = dateB - Date.now();
var yrs = Math.floor(diff / 31536000000);
var mos = Math.floor(diff / 2678400000) % 12;
var days = Math.floor(diff / 86400000) % 31;
var hrs = Math.floor(diff / 3600000) % 24;
var mins = Math.floor(diff / 60000) % 60;
var secs = Math.floor(diff / 1000) % 60;
var mill = diff % 1000;
var str =
yrs + ' Years ' +
mos + ' Months ' +
days + ' Days ' +
hrs + ' Hours ' +
mins + ' Mins ' +
secs + ' Secs ' +
mill + ' Mill';
el.innerText = str;
}
If you're using javascript for comparing dates or counting number of days, you might have some problems. You should use a library for better results.
I recommend you to use http://momentjs.com/ for date or time function. It's easy to use and much more flexible.
This should answer your question: Countdown timer using Moment js
try this..
function checkFromDate(sender, args) {
if (sender._selectedDate > new Date()) {
alert("You cannot select a day future than today.");
sender._selectedDate = new Date();
sender._textbox.set_Value(sender._selectedDate.format(sender._format))
}
}
I'd like to calculate the elapsed time between two dates. I saw some examples on the internet (most of them on this site), but found nothing useful. I'd like to write a function can call like this:
calculateDifference('2012-02-01 15:31')
There is no second parameter, since it is the current date. I have a code I'm currently using, which is:
function get_time_diff(_datetime )
{
var datetime = new Date( _datetime ).getTime();
var now = new Date().getTime();
if( isNaN(datetime) )
{
return " on " + _datetime;
}
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var date_diff = new Date( milisec_diff );
var respvalue ='';
if (days > 0) {
respvalue += days + " day(s), ";
}
if (date_diff.getHours() > 0) {
respvalue += (date_diff.getHours() - 1) + " hour(s) and ";
}
respvalue += date_diff.getMinutes() + " minute(s) ago.";
return respvalue;
}
And the result is and should be:
1 day(s), 14 hour(s) and 17 minute(s)
For some reasons there are differences (when 1 day passed it shows 0 etc) and it works only with chrome, in IE and FF it returns with the date I passed as the parameter.
Once again: I'd like to calculate the difference between the current date and a given date in the next format:
1 day(s), 14 hour(s) and 17 minute(s)
I don't care about the months, years. Only hours, mins and secs. Thank you in advance!
Try this:
function get_time_diff(_datetime )
{
var datetime = new Date( _datetime ).getTime();
var now = new Date().getTime();
if( isNaN(datetime) )
{
return " on " + _datetime;
}
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var hours = Math.floor(milisec_diff / (1000 * 60 * 60) - days * 24);
var minutes = Math.floor(milisec_diff / (1000 * 60) - days * 24 * 60 - hours * (60));
var respvalue ='';
if (days > 0) {
respvalue += days + " day(s), ";
}
if (hours > 0) {
respvalue += hours + " hour(s) and ";
}
respvalue += minutes + " minute(s) ago.";
return respvalue;
}
The problem is that your date format is not valid, so Firefox can't parse your strings as dates.
You can use
function get_time_diff(datetime) {
var milisec_diff = Math.abs(new Date() - new Date(datetime)),
diff = new Date(milisec_diff),
days = milisec_diff / 3600e3 / 24 | 0,
hours = diff.getUTCHours(),
respvalue = '';
if (days)
respvalue += days + " day(s), ";
if (hours)
respvalue += hours + " hour(s) and ";
respvalue += diff.getUTCMinutes() + " minute(s) ago.";
return respvalue;
}
get_time_diff('2012-02-01T15:31Z');
Where the date 2012-02-01T15:31Z is in ISO8601, and the Z means UTC time (note some browsers may not support it).
This seems simplest to me:
http://jsbin.com/tusul/9/edit
// end date is optional, it will assume the current date if not supplied.
// if timezone is not supplied, it will assume local browser time.
function calculateDateDiff(beginDate, endDate) {
var currentDate;
if (typeof(endDate) == 'undefined') {
currentDate = new Date();
} else {
currentDate = new Date(endDate);
}
var targetDate = new Date(beginDate);
var differenceDate;
if (currentDate > targetDate) {
differenceDate = new Date(currentDate - targetDate);
} else {
differenceDate = new Date(targetDate - currentDate);
}
return('Days: ' + (differenceDate.getUTCDate() -1) + ', Hours: ' + differenceDate.getUTCHours() + ', Minutes: ' + differenceDate.getUTCMinutes() + ', Seconds: ' + differenceDate.getUTCSeconds());
}
console.log(calculateDateDiff('05-22-2014 01:02:03', '05-22-2014 02:03:04'));
console.log(calculateDateDiff('05-22-2014 01:02:03', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03Z', '05-22-2014 02:03:04Z'));
console.log(calculateDateDiff('05-22-2014 01:02:03Z', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03-500', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03+1000', '05-22-2014 02:03:04-600'));
I've been working on this script to get the difference between 2 dates. But the hours will mess up the script (http://jsfiddle.net/HuGvd/).
When the script enters a new month new the same day the script stops working correctly. I've also tried adding minutes to this script with no luck really need help with this one guys.
function getDateDiff(timestamp) {
if (null === timestamp || timestamp === "" || timestamp === "undefined") return "?";
var splitDate = ((timestamp.toString().split('T'))[0]).split('-');
var splitTime = ((timestamp.toString().split('T'))[1]).split(':');
var d1 = new Date();
var d1Y = d1.getFullYear();
var d2Y = parseInt(splitDate[0], 10);
var d1M = d1.getMonth() + 1;
var d2M = parseInt(splitDate[1], 10);
var d1D = d1.getDate();
var d2D = parseInt(splitDate[2], 10);
var d1H = d1.getHours();
var d2H = parseInt(splitTime[0], 10);
var diffInHours = (d1H + 24 * d1D + 30) - (d2H + 24 * d2D + 30);
if (diffInHours < 24) return diffInHours + " hour";
var diffInDays = (d1D + 30 * d1M + 12) - (d2D + 30 * d2M + 12);
if (diffInDays < 7) return diffInDays + " days";
else if (diffInDays >= 7 && diffInDays < 14) return "1 week";
else if (diffInDays >= 14 && diffInDays < 30) return Math.floor(diffInDays / 7) + " weeks";
var diffInMonths = (d1M + 12 * d1Y) - (d2M + 12 * d2Y);
if (diffInMonths <= 1) return "1 month";
else if (diffInMonths < 12) return diffInMonths + " months";
var diffInYears = Math.floor(diffInMonths / 12);
if (diffInYears <= 1) return "1 year";
else if (diffInYears < 12) return diffInYears + " years";
}
Date/time functionality is extremely complex with more edge cases than you can possibly cover... don't roll your own solution, use built-in functionality. You can find the number of milliseconds between two dates in javascript like this:
var now = new Date();
var then = new Date(timestamp);
var diffMS = now - then;
From there, it's not too difficult to convert to whatever unit your want based on how you want to display it.
http://jsfiddle.net/AMDXq/
As a side note, this is a fairly common problem. I haven't looked, but I'm sure there's a plugin or library out there for this.
Here is a solution for finding the difference between two dates. The strategy is to convert strings to date objects, then calculate the difference and return an array of values for years, months, days, etc.
I've added a parameter for "precise" so that by default it returns a value in whole days (e.g. 2013-08-13T23:59:59Z to 2013-08-14T00:00:01Z is one day) or precise (where the above difference is 2 seconds).
// Expects start date to be before end date
// Default is to deal in whole days. For precise differences
// (hours, minutes and seconds), set precise to true
function dateDifference(start, end, precise) {
var timeDiff, years, months, days, hours, minutes, seconds;
// Copy date objects so don't modify originals
var s = new Date(+start);
var e = new Date(+end);
console.log(s, e);
// If not precise, set h,m,s to zero
if (!precise) {
s.setUTCHours(0,0,0,0);
e.setUTCHours(0,0,0,0);
console.log(s, e);
}
// Get estimate of year difference
years = e.getUTCFullYear() - s.getUTCFullYear();
// Add difference to start, if greater than end, remove one year
// Note start from restored start date as adding and subtracting years
// may not be symetric
s.setFullYear(s.getUTCFullYear() + years);
if (s > e) {
--years;
s = new Date(+start);
s.setFullYear(s.getUTCFullYear() + years);
}
// Get estimate of months
months = e.getUTCMonth() - s.getUTCMonth();
months += months < 0? 12 : 0;
// Add difference to start, adjust if greater
s.setUTCMonth(s.getUTCMonth() + months);
if (s > e) {
--months;
s = new Date(+start);
s.setUTCFullYear(s.getUTCFullYear() + years);
s.setUTCMonth(s.getUTCMonth() + months);
}
// Get remaining time difference
timeDiff = e - s;
days = timeDiff / 8.64e7 | 0;
hours = (timeDiff % 8.64e7) / 3.6e6 | 0;
minutes = (timeDiff % 3.6e6) / 6e4 | 0;
seconds = ((timeDiff % 6e4) / 1e3).toFixed(3);
console.log(years, months, days, hours, minutes, seconds);
return [years, months, days, hours, minutes, seconds];
}
// Simple caluculation of days between two ES5 date objects
function daysDifference(start,end) {
return ((end - start) / 8.64e7).toFixed(2);
}
// Expects input in ISO8601 format: yyyy-mm-ddThh:mm:ss.sssZ
function dateFromString(s) {
s = s.split(/\D/);
s[6] = s[6]? ('0.'+ s[6]) * 1000 : 0;
return new Date(Date.UTC(s[0],--s[1],s[2],s[3],s[4],s[5],s[6]));
}
function getDateDiff(start, end, precise) {
var d = dateDifference(dateFromString(start), dateFromString(end), precise);
return d[0] + ' years, ' + d[1] + ' months, ' + d[2] + ' days' +
(precise? ', ' + d[3] + ' hours, ' + d[4] + ' minutes and ' + d[5] + ' seconds' : '') ;
}
function getDaysDiff(start, end) {
var d = daysDifference(dateFromString(start), dateFromString(end));
return d + ' days';
}
</script>
<!-- Some HTML to show how to use it -->
<form onsubmit="this.doCalc.onclick(); return false;">
<label for="startDate">Start date (yyyy-mm-dd)<input name="startDate" id="startDate"
value="2012-08-09T22:15:03.22" size="25"></label>
<br>
<label for="endDate">End date (yyyy-mm-dd)<input name="endDate" id="endDate"
value="2013-08-13T12:10:03.22" size="25"></label>
<br>
<label for="dateDifference">Date difference: <input name="dateDifference" readonly size="100"></label>
<br>
<label for="daysDifference">Days difference: <input name="daysDifference" readonly size="100"></label>
<br>
<label for="precise"><input type="checkbox" value="precise" name="precise" id="precise">Precise?</label>
<br>
<input type="button" value="Calculateā¦" name="doCalc" onclick="
this.form.dateDifference.value = getDateDiff(this.form.startDate.value, this.form.endDate.value,
this.form.precise.checked);
this.form.daysDifference.value = getDaysDiff(this.form.startDate.value, this.form.endDate.value);
">
<input type="reset">
</form>
I am creating an app in which I need to calculate the difference time between current time and previous time which will come from the database and need to display on list. The app works fine in India, but when the same app runs in US than difference time showing in -2560 seconds, or something like that. Why is this?
The code that I used to calculate the difference between times:
var timeAgoInWords = function(date) {
try {
var now = Math.ceil(Number(new Date()) / 1000),
dateTime = Math.ceil(Number(new Date(date)) / 1000),
diff = now - dateTime,
str;
if (diff < 60) {
return String(diff) + ' seconds ago';
} else if (diff < 3600) {
str = String(Math.ceil(diff / (60)));
return str + (str == "1" ? ' minute' : ' minutes') + ' ago';
} else if (diff < 86400) {
str = String(Math.ceil(diff / (3600)));
return str + (str == "1" ? ' hour' : ' hours') + ' ago';
} else if (diff < 60 * 60 * 24 * 365) {
str = String(Math.ceil(diff / (60 * 60 * 24)));
return str + (str == "1" ? ' day' : ' days') + ' ago';
} else {
return Ext.Date.format(new Date(date), 'jS M \'y');
}
} catch (e) {
return '';
}
};
The above function I am calling from an itemTpl, the below code is where CreatedDate will come from database which I save when a user submits a review comment and am passing as parameter to function.
this.posted(Ext.Date.parse(values.CreatedDate, "Y-m-d g:i:s"))
posted: timeAgoInWords
And here's how I store the current date and time into the database:
Ext.Date.patterns = { ISO8601Long: "Y-m-d H:i:s" };
var date = new Date();
var now = Ext.Date.format(date, Ext.Date.patterns['ISO8601Long'])
It is a timezone issue. Since the USA is behind IST, the date in seconds from epoch, is giving you a date in the past. This difference thus is negative, since the date you have entered still has to happen in the USA. It is recommend you change all times to UTC before you do any calculations for finding difference in times. You could also calculate the difference on your own server.