Using jquery countdown timer with mysql datetime? - php

I know this question has been asked many times as I have found a few on google and also on stackoverflow.
but none of them explained how to format my datetime in my php so it works in combination with jquery countdown timer. so I am going to ask it here in a hope i get someone shed a light on this for me.
Basically what i am trying to do is to create a countdown timer which will work with mysql datetime.
the datetime is stored in mysql so All need to do is to get the correct format in my php so the countdown timer could work with it.
I am using this plugin: http://keith-wood.name/countdown.html
and here is what i have so far:
PHP formatting:
$end_date = date("m d Y H:i:s T", strtotime($row["end_date"]));
Jquery/Javascript code:
<script type="text/javascript">
$(function(){
var countdown = $('#countdown'),
ts = new Date(<?php echo $end_date * 1000; ?>),
finished = true;
if((new Date()) > ts)
{
finished = false;
}
$('#defaultCountdown').countdown({
timestamp : ts,
callback : function(days, hours, minutes, seconds)
{
var message = "";
message += days + " days, ";
message += hours + " hours, ";
message += minutes + " minutes, ";
message += seconds + " seconds ";
message = (finished ? "Countdown finished" : "left untill the New Year");
countdown.html(message);
}
});
});
</script>
when i run this code, all i get is 0 hours, 0 minutes, 0 seconds.
I can only suspect that the issue is from formatting the datetime in my php section!
or am i missing something else as well?
okay I have managed to minify the code to this:
<script type="text/javascript">
$(document).ready(function () {
$('#defaultCountdown').countdown({
until: new Date(<?php echo $end_date; ?>),
compact: true
});
});
</script>
and changed the php to this:
$end_date = date("Y, n, j, G, i, s", strtotime($row["end_date"]));
However, the time shown in the coutdown timer is wrong (way off).
the $end_date is: September 22 2013 23:30:00 GMT in mysql datetime
but the jquery countdown timer is showing:
34d 06:21:48
2013, 9, 22, 23, 30, 00
34days and 6 hours blah blah is absolutely wrong!
what am i doing wrong here now?

The JavaScript Date object is constructed as follows:
Date(year, month, day, hours, minutes, seconds, milliseconds)
That means you probably should be doing something along these lines:
$end_date = date("Y, n, j, G, i, s", strtotime($row["end_date"]));
Sources:
JavaScript Date-object
PHP date-function
EDIT:
In addition, I seem to have found the problem in the jQuery Countdown manual:
A note on Date - the JavaScript Date constructor expects the year,
month, and day as parameters. However, the month ranges from 0 to 11.
To make explicit what date is intended (does a month of 3 mean March
or April?) I specify the month from 1 to 12 and manually subtract the
1. Thus the following denotes 25 December, 2010.
So, you'd have to split the string, substract 1 from the month and rebuild...
$tmp_date = explode(', ', $end_date);
$tmp_date[1] = $tmp_date[1] - 1;
$end_date = implode(', ', $tmp_date);
Link to jsFiddle

Related

php and javascript date not match

i have a strange questions.
In my php page i try to print dates with php function and javascript function.
My code is:
// 04 09 2013 09:47:28
<script>document.write(new Date());</script>
// 04 09 2013 09:48:17
<?php echo date('d m Y H:i:s');?>
Why the dates are not equal, but there is a litte second of difference?
I would have same dates beetween php and javascript.
---UPDATE CODE---
function startCounter(){
start = new Date(<?php echo time(); ?> * 1000);
end = new Date(<?php echo $end_ts; ?> * 1000);
timer = setInterval(updateCounter, refreshInterval);
}
function updateCounter(){
var now = new Date();
var distance = new Date(end - now);
}
Thank you very much.
First of all you need to understand the time being printed by php is the server time and time being printed by javascript is your local computer time. If the time between those 2 is different then it can show different time.
Like others said, javascript time is client time and php time is server time.
To solve the problem try something simliar to:
<? $time = time(); ?>
<script>document.write(new Date(<?=$time*1000?>));</script>
<?=date('Y-m-d H:i:s', $time')?>

How do I do this with PHP not Javascript (timestamp conversion)

I have written this Javascript to convert a timestamp to something readable. It works perfectly. However I need to do it with PHP but don't know how. Obviously I don't want an alert of the time, but I'd like to have it as a PHP variable. Any ideas?
<script>
var bmsTime ="39845.03";
var date = new Date('31 dec 1899');
date.setTime(date.getTime() + bmsTime* 24 * 60 * 60 *1000);
alert (date);
</script>
Use the date function, it takes an additional parameter called timestamp. But in php timestamp is number of seconds, not milliseconds as in javascript, so divide it by 1 000:
echo date('l jS \of F Y h:i:s A', $javascript_timestamp / 1000);
The short answer: You cannot properly do this, as you do not know the timezone the browser/client is using.
Long answer (using the server timezone - or whatever is configured for PHP):
$bmsTime = 39845.03;
$date = mktime(0, 0, 0, 12, 31, 1899);
$date += $bmsTime * 24 * 60 * 60; // $date are the seconds relative to "the epoc" (1970-01-01 UTC)
echo date('c', $date);

Help implementing past date validation

I need to implement something that checks if a given date is greater than today. If for example, I input a date of April 19, 2011 while today is April 15, 2011, there should be some validator/pop up error. How do I implement this?
I have my system date (today's date) working fine through php. I just don't know how to create a validation/error message when the user inputs a higher date than today.
It can be done with PHP (on server side) and with JavaScript (on client side, in browser).
Here is an example of how to do it on JavaScript:
var currentTime = new Date()
month = currentTime.getMonth(),
day = currentTime.getDate(),
year = currentTime.getFullYear(),
today = year + "-" + month + "-" + day;
var users_day = '2011-04-19';
if (users_day > today) {
alert ("Entered day is greater than today");
}
else {
alert ("Today is greater than entered day");
}
For example (in PHP)
date_default_timezone_set(date_default_timezone_get()); // not necessary here
$today = strtotime('2011-04-15');
$users_day = strtotime('2011-04-19');
if ($users_day > $today) {
echo "Error";
}
else {
echo "OK";
}
Example above outputs
Error
...because April 19, 2011 (user's input) is greater than April 15th, 2011 (today).

How can I get how old a user is/ how long it has been by comparing dates with PHP/javascript?

I'm looking for a way to compare dates and find the difference with PHP or jQuery (JavaScript). For instance if a user's birthday is 1/16/95 or January 16, 1995 and today is December 24, 2011 how could I get "x Years and x Days"? Or if some one were to save a file and the date of creation is 1/16/95 or January 16, 1995 and 25 seconds passed since creation how could I get that time?
Take a look at DateTime::diff:
PHP Manual
Your code could look like this:
$datetime1 = new DateTime('1994-12-16');
$today = new DateTime();
$interval = $datetime1->diff($datetime2);
echo $interval->format('%y years %d days');
If I where you I would use the PHP time() function.
This value is always unique and is always interpreted the right way.
You can always use strtotime php function to convert a string to a timestamp.
Its easy calculating with those timestamps because difference A-B gives you time difference in seconds.
Hope it helps
You just need to convert the date to UNIX time (seconds since Jan 1, 1970), then subtract from "now". That will give you the difference in seconds, which you can then convert to a time string.
PHP has, as expected, some built-in stuff to do it, so it's very simple:
$birth = new DateTime('12/16/94');
$age = $birth->diff(new DateTime("now"));
echo $age->format('%y years and %d days');
(see valid time strings)
In Javascript, you need to do it yourself (but I did it for you):
function timeSince(_date){
// offset from current time
var s = Math.floor( (+new Date - Date.parse(_date)) / 1000 )
, day = 60*60*24
, year = day*365;
var years = Math.floor(s/year)
, days = Math.floor(s/day) - (years*365)
// handle plurals
, ys = ' year' + (years>1 ? 's' : '')
, ds = ' day' + (days>1 ? 's' : '');
return years + ys + ' and ' + days + ds;
};
timeSince(new Date('06/25/1985')); // => '25 years and 278 days'
This is getting the difference in seconds from the date to now, then dividing the value by an year/day's length in seconds. The allowed time strings are much more limited in js though.

Want to display the current date/time

Hi I'm using php and sql through odbc to write a program and i hav got abit stuck in a part where i want to display the current date/time in the format date('Y-m-d H:i:s) but it only displays the gmt time. I want to add 8hours to it.Can any of you b able to help me.Thank you so much
Check out date_default_timezone_set. You can do something like:
date_default_timezone_set('America/Los_Angeles');
print 'Current datetime is: ' . date('Y-m-d H:i:s');
You could use that to set the timezone to whatever timezone you need time to be at, and then use date normally. Alternatively, you can do this, using strtotime:
print 'Current datetime is: ' date('Y-m-d H:i:s', strtotime('+8 hours'));
If you're looking for a way to display a timestamp in a user's local time, you can use JavaScript:
function showtime(t)
{
if (t == 0)
{
document.write("never");
return;
}
var currentTime = new Date(t);
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
document.write();
if (minutes < 10){
minutes = "0" + minutes;
}
if (seconds < 10){
seconds = "0" + seconds;
}
document.write(month + "/" + day + "/" + year + " " +
hours + ":" + minutes + ":" + seconds + " ");
if(hours > 11){
document.write("PM");
} else {
document.write("AM");
}
}
Then if you need to display a time, just make a call to it in the HTML and splice in the value from PHP:
<script type="text/javascript">showtime(<?=$time."000"?>)</script>
I would steer clear of the timezone method.
If i understood correctly, you want to add time, thus change it. An example could be, A task has been created NOW, and must be complete in 8 hours. The timezone method would only change the display of the date and time. Only change the timezone setting if you know your visitor's timezone, and datetime's must be shown relative to them.
Now: 1234418228 is 2009/02/12 00:57:08 in Montreal or 2009/02/11 09:57:08 in San Francisco. It's the exact same moment.
Appending to the first answer, date() and strtotime() are your friends.
strtotime( "+8 hours", $now )
$now being a timestamp of when it's supposed to relate to. So if your start time isn't time(), you can still use that. eg
strtotime( "+8 hours", strtotime( "2009/03/01 00:00:00" ); (8AM on 2009/03/01)
However, when dealing with intervals counted in weeks, or less, i prefer doing it 'mathematically'
$StartTime = strtotime( "2009/03/01 13:00:00" );
$EndTime = $StartTime + ( 8 * 60 * 60 );
date( "Y/m/d H:i:s", $EndTime ) ==> "2009/03/01 21:00:00"
3600 seconds in an hour, 86400 in a day.
You can't use this method for months, quarters or years because the number of seconds they last varies from one to the next.
If you want to use time for a certain timezone, then using date_default_timezone_set() is preferred. anyway you can provide the date() function another parmater: int timestamp. an integer representing the timestamp you would like date() to return the information about.
so if you would like to show date('Y-m-d H:i:s') for now you can use this:
$now = date('Y-m-d H:i:s', time() ); // time() returns current timestamp.
// if you omit the second parameter of date(), it will use current timestamp
// by default.
$_8hoursLater = date('Y-m-d H:i:s', time()+60*60*8 );
$_8hoursBefore = date('Y-m-d H:i:s', time()-60*60*8 );

Categories