calculate time difference and display popup based on time difference - php

im writing a small calendar based on php and jquery which has the a function to calculate the time difference and display a popup 15 minutes before.
Can some one tell me how can i calculate the time difference in minutes and popup 15 minutes before.
my time is saved as
18-07-2012 15:13:54

jsBin demo
var php = '19-07-2012 03:00:00'.split('-');
var phpDate = php[1]+'/'+php[0]+'/'+php[2];
var phpTime = new Date(phpDate).getTime();
var currTime = new Date().getTime();
var difference= phpTime-currTime;
var leftMin = Math.ceil( difference/(1000*60) );
$('#test').text(leftMin+' MINUTES LEFT!');
Code explanation:
To get the remaining time I've done a millisecond comparison of the php returned time in milliseconds from Jan. 1 1970
and the current time in ms from Jan 1 1970 - subtracting the two values and getting the milliseconds difference. To calculate that difference in minutes I've just done:
var leftMin = Math.ceil( difference/(1000*60) );
The trick was to get the right time format and to revert your (php) returned time to that format too.
The default format looks like: MONTH/DAY/YEAR HOURS:MINUTES:SECONDS
To convert the php returned time '19-07-2012 03:00:00'to that one, I used:
var php = '19-07-2012 03:00:00'.split('-'); // split in array fractions
var phpDate = php[1]+'/'+php[0]+'/'+php[2]; // reposition array keys and add '/'
which returns: 07/19/2012 03:00:00 and now we can compare it to the current time e.g.:
07/19/2012 03:45:21
To retrieve the ms from your converted php time we can use:
var phpTime = new Date(phpDate).getTime(); // get "ms from our string
and for the current time we just take:
var currTime = new Date().getTime(); // get "ms from 1/1/1970
Now having our two milliseconds values we can simply subtract them to get the remaining time:
var difference= phpTime-currTime;

Check PHP's DateTime::diff! Maybe it helps you.

var dateStr = '18-07-2012 15:13:54'//Day-Month-Year
var dateArray = dateStr.split('-')
var d1 = new Date(dateArray[1]+'-'+dateArray[0]+'-'+dateArray[2])
var dateStr2 = '18-07-2012 14:10:54'//Day-Month-Year
var dateArray2 = dateStr2.split('-')
var d2 = new Date(dateArray2[1]+'-'+dateArray2[0]+'-'+dateArray2[2])
var minutes = (d1-d2)/1000/60
-edit; revised code below:-
function timeDiff(date1, date2){
//date format: Day-Month-Year
var dateArray = date1.split('-')
var d1 = new Date(dateArray[1]+'-'+dateArray[0]+'-'+dateArray[2])
var dateArray2 = date2.split('-')
var d2 = new Date(dateArray2[1]+'-'+dateArray2[0]+'-'+dateArray2[2])
var minutes = (d1-d2)/1000/60
return minutes;
}
if(timeDiff('18-07-2012 15:13:54', '18-07-2012 14:59:54')<=15){
alert('popup')
}

php has an mktime() function (http://php.net/manual/en/function.mktime.php) which takes in a hours, minutes, seconds, month, day, year and calculates the seconds since the epoch (in like 1971). Then you can subtract 15*60 use the date() function to go from seconds back to a date format. (http://php.net/manual/en/function.date.php)

Related

Elapsed time from a given time in the database

I have a HTML table which has records pulled in from the database. I'm using PHP/MySQL.
The Column in my table named "Timer" is not retrieved from the database. I need the elapsed time (from the a specific time in the database) to be shown here. For Example, let's say the time now is 21 Feb 2013 6.20 pm and the time in the database is 21 Feb 2013 5.50 pm, I need the Timer Column to Display 00:30:00 (as thirty minutes have passed since 5.50PM). It must be a Running timer (Not a static one which can be computed by using MySQL datetime difference) so whoever accesses the page should be able to see the same elapsed time. I also need to stop the timer when I click another button.
I saw other posts here related to this question like this Elapsed Time to database from Javascript timer but I think what I'm asking is different. I'm still confused on how to go about doing this. I've very little Javascript knowledge, would be greatful if you could help me with it or refer me to the right place. Thank you!
This can be achieved with very little Javascript.
Assuming that the "Created" time is rendered dynamically in the table with format dd MMM yyyy hh:mm:ss, something like this should do the trick:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
ElapsedTimeLogger = function(dateElementId, elapsedElementId, interval) {
var container = $(elapsedElementId);
var time = parseDate($(dateElementId).text());
var interval = interval;
var timer;
function parseDate(dateString) {
var date = new Date(dateString);
return date.getTime();
}
function update() {
var systemTime = new Date().getTime();
elapsedTime = systemTime - time;
container.html(prettyPrintTime(Math.floor(elapsedTime / 1000)));
}
function prettyPrintTime(numSeconds) {
var hours = Math.floor(numSeconds / 3600);
var minutes = Math.floor((numSeconds - (hours * 3600)) / 60);
var seconds = numSeconds - (hours * 3600) - (minutes * 60);
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
var time = hours + ":" + minutes + ":" + seconds;
return time;
}
this.start = function() {
timer = setInterval(function() {update()}, interval * 1000);
}
this.stop = function() {
clearTimeout(timer);
}
}
$(document).ready(function () {
var timeLogger = new ElapsedTimeLogger("#date", "#elapsed", 2);
timeLogger.start();
$("#stop_timer").click(function() {
timeLogger.stop();
});
$("#start_timer").click(function() {
timeLogger.start();
});
});
</script>
</head>
<body>
<table border="1">
<tr><th>Created</th><th>Timer</th></tr>
<tr><td id="date">21 Feb 2013 12:30:00</td><td id="elapsed"></td></tr>
</table>
<input id="stop_timer" type="button" value="Stop timer"></input>
<input id="start_timer" type="button" value="Start timer"></input>
</body>
</html>
Copy the code above into a file, say index.html, and open it in a browser. I tested it on Chrome.
It should update the elapsed time every 2 seconds, but you may change the update interval to something that suits you, e.g. to make it update every 5 minutes:
new ElapsedTimeLogger("#date", "#elapsed", 300);
The general concept is to parse the rendered "Created" date into an epoch timestamp (in milliseconds) and then compute its difference with the current system time. To get the elapsed time updating dynamically you use Javascript's setInterval function. To stop updating the elapsed time use Javascript's clearTimeout function.
I lifted the prettyPrintTime function from powtac.
If you are looking for a pure html base solution with the sql to do the dynamic changes, it is impossible. If you need to do a running timer you will need to use JS. (can be done with the help of css5 as well).
You'd want to use PHP to retrieve the time from the database, then use Javascript to display a timer that's counting from the time retrieved. You should be able to find available premade Javascript scripts that can do this quite easily. Here's one I found. I have no idea if it's the best for your needs, but it was amongst the first results. Just snip off the parts not needed, like the year, month, etc.
http://praveenlobo.com/techblog/javascript-countup-timer/

get date with timezone javascript

I want to compare date and with date in user timezone after user's login.
I get user's timezone with php.
now How to I take current date/time in javascript of user's timezone current time.
#everyone answered:
I don't need current local system timezone or offset in seconds.
I need users current time with dynamic time I get in php.
For example:
I have 'Asia/Kolkata' or 'America/Denver' or whatever that will be dynamic by php.
Now I can save it to hidden value so that I can get it with Javascript
and than I need current date of this timezone same like Javascript gives date object.
JavaScript uses the system's time zone. You can get the offset via GetTimezoneOffset
<script>
var date=<?php echo date("Y/m/d")?>
</script>
this might help you
Try like this
<script>
var date = '<?php echo date("Y/m/d");?>';
alert(date);
</script>
deeply you can also try like this
var today = new Date();
var localoffset = -(today.getTimezoneOffset()/60);
var destoffset = -4;
var offset = destoffset-localoffset;
var d = new Date( new Date().getTime() + offset * 3600 * 1000);
alert(d);
there you can get
Try this:
// date() function
var currDate = new Date()
var n = currDate.getTimezoneOffset();
You can send UTC string
strtotime("2013-02-08 00:00:00");
After that you would have seconsd, that you can convert simple to JS Date:
var utcString = 1360263600 /*AJAX result must be here*/;
new Date(utcString*1000);
You can use Date Object of JavaScript to get user's local system..
for example you can use following:
var d = new Date();
var time = d.getTime();
alert(time);
this will alert the the number of milliseconds since midnight.
You can send this time to your server and compare the both.
For more functions and details you can visit JavaScript Date Object
I am from Taiwan and it returns "+8" for me.
Working example
JS
function timezone() {
var offset = new Date().getTimezoneOffset();
var minutes = Math.abs(offset);
var hours = Math.floor(minutes / 60);
var prefix = offset < 0 ? "+" : "-";
return prefix+hours;
}
$('#result1').html(timezone());
HTML
<div id="result"></div>
Result
+8
I would recommend to use moment.js with moment timezone.
Then you can do something like:
moment().tz("Asia/Kolkata").format();

Convert facebook time zone into my local time zone as facebook does

I am using facebook apis and getting created_time as
2012-06-06T16:20:43+0000
I have posted this status at about
21:57 (IST)
and i am getting 2012-06-06T16:20:43+0000
any help will be appreciated, to get the same time as i have posted to get the exact updates.
you can convert any timezone using this code:
$timestamp = strtotime("2012-06-06T16:20:43+0000"); //here you put your string with the tie
$dtime = new DateTime();
$dtime->setTimestamp($timestamp);
$localtz = new DateTimeZone("Asia/Calcutta"); //choose the correct PHP timezone
$dtime->setTimeZone($localtz); //we apply the timezone
$stringtime = $dtime->format('Y-m-d\TH:i:sO'); //here you return the time in the same format as facebook
$unixtime = $dtime->format('U'); //here u get the unix timestamp format of the same string
print $stringtime;
I've written a function earlier for this task,
I've updated it for your needs,
var fbDateFix = function(date){
var local = new Date(date.replace(/-/g,'/').replace('T',' ').replace('+0000',''));
local.setSeconds(local.getSeconds() + 19800);
return local;
}
var padZero = function(t){
if(t<10){
return '0' + t;
}
return t;
}
var d = fbDateFix('2012-06-06T16:20:43+0000');
console.log(d);
var month = padZero(+d.getMonth()+1);
var date = padZero(+d.getDate());
var hour = padZero(+d.getHours());
var min = padZero (+d.getMinutes());
var sec = padZero (+d.getSeconds());
console.log(d.getFullYear() + '-' + month + '-' + date + 'T' + hour + ':' + min + ':' + sec + '+0000')
Edit:
This works for me in php,
date_default_timezone_set('Asia/Calcutta');
$timestamp = strtotime('2012-06-06T16:20:43+0000');
$local_datetime = date('c',$timestamp);
echo $local_datetime;
It looks like the date returned to you is a UTC datetime. You need to convert it to your local timezone (IST)...
See the following SO question for converting datetimes using php:
php convert datetime to UTC
You can use PHP's strtotime to convert created_time to a UNIX timestamp. Then you can add or subtract your time zone offset (IST is UTC+05:30).

>Javascript Comparing 2 dates

I have this code in comparing dates
var startDate = jQuery("#startDate_field_id").val();
var endDate = jQuery("#endDate_field_id").val();
var startDateSplit = startDate.split("-");
var endDateSplit = endDate.split("-");
var start = new Date();
var end = new Date();
start.setFullYear( startDateSplit[0], startDateSplit[1], startDateSplit[2] );
end.setFullYear( endDateSplit[0], endDateSplit[1], endDateSplit[2] );
if( end < start ) {
alert("End Date should be less than Start Date of the Event");
}
The value of #startDate_field_id is 2011-10-05
white the value of $endDate_field_id is 2011-10-04
What do you think is the reason why this isn't working.
Any help would be greatly appreciated and rewarded.
Thanks! :)
I think your first problem is that you are using the Date object incorrectly. You are passing three arguments to the setFullYear() method, which only takes a single argument, a 4 digit year.
var start = new Date();
var end = new Date();
start.setFullYear( startDateSplit[0], startDateSplit[1], startDateSplit[2] );
end.setFullYear( endDateSplit[0], endDateSplit[1], endDateSplit[2] );
You might want to try something like this:
var start = new Date(startDateSplit[0], startDateSplit[1] - 1, startDateSplit[2])
var end = new Date(endDateSplit[0], endDateSplit[1] - 1, endDateSplit[2]);
I'd use UNIX epoch timestamps for the comparison:
if (end.getTime() > start.getTime()) {
alert('...');
}
Because setFullYear method month parameter accept 0..11, means 9 is October.
why not use
var start = new Date(startDate);
var end = new Date(endDate);
var start = new Date(Number(startDateSplit[0]), Number(startDateSplit[1])-1, Number(startDateSplit[2]));
var end = new Date(Number(endDateSplit[0]), Number(endDateSplit[1])-1, Number(endDateSplit[2]));
or simply:
I am not sure I correctly understand your question .
I guess you want make sure that the end date must be greater than start date.
your code will work fine if you cahnge the if condition .And i just changed the alert message too to get proper meaning
Check this DEMO .

Timestamp to date with Javascript. How?

I create a timestamp with strtotime php function. My question is how to "reverse" timestamp to year, month, date, ... seconds etc using javascript ?
var date = new Date(phptimestamp*1000);
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
//etc...
var date = new Date(seconds*1000);
where milliseconds is seconds since Jan 1970.
var date = new Date(timestamp*1000);

Categories