php and javascript date not match - php

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')?>

Related

Using jquery countdown timer with mysql datetime?

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

PHP Date to Javascript Date becomes Time Difference?

I'm using JS DataTable and the Date Column must be sortable. But it can't sort as JS assume the Dates imported as the Strings. (It doesn't sort in actual chronological order. Just in string order)
Then as i googled, i start realized that JS can only sort JS Dates. Means, i need to convert PHP Date into JS Dates.
But i can't get it properly yet. What i did is:
<script>
var jsDate = new Date(
<?php echo $phpDate_y; ?>,
<?php echo $phpDate_m; ?>,
<?php echo $phpDate_d; ?>
); // $phpDate will be "2012-04-30";
</script>
But on rendering, the jsDate is transformed as:
Thu Oct 03 1935 00:00:00 GMT+0730 (MALST)
FAR DIFFERENT!!
And, my timezone location is Singapore.
Is there any other proper way pls :(
You can pass a full date string to the JS Date object to construct it so try passing $phpDate in one of the ISO date formats into the Date constructor instead of splitting it the way you're doing it.
// $phpDate = '2012-08-17 12:29:06'
var jsDate = new Date("<?php echo $phpDate; ?>");
Try to use date_default_timezone_set('America/Los_Angeles');
first line in your PHP scripts.
php.net/manual/en/function.date-default-timezone-set.php

Send PHP date to JavaScript date format

I want to pass my PHP server time to my JavaScript file.
PHP Code:
date_default_timezone_set('Australia/Perth');
echo date("r");
JavaScript:
$.get('time.php', function(data) {
today = new Date(data);
closing = new Date(data);
});
The PHP code returns Sun, 18 Mar 2012 12:01:23 +0800 which is correct time for Australia/Perth. But this returns an invalid JavaScript date object.
When I try to convert it to timestamp like:
echo strtotime(date("r"));
I get the JavaScript date Sun Mar 18 2012 04:03:14 GMT+0000 (WET) (this is the value of today js var)
If I use:
echo gmstrftime('%s');
I get: Sat Mar 17 2012 20:04:30 GMT+0000 (WET).
Can anyone please help me out?
The PHP code in Luna's answer with echo date isn't exactly like JavaScript code. This will mimic the JavaScript code exactly:
echo date('D M d Y H:i:s O');
You could also just leave the PHP code as it is and parse the date using JavaScript:
var date = new Date(Date.parse(DATE));
Then even things like this would work:
new Date(Date.parse('11 March 2017'));
Which outputs via a console log (GMT+1000 is because I am in Australia):
Sat Mar 11 2017 00:00:00 GMT+1000
More information is here: https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
$.get('time.php', function(data) {
today = new Date(data);
closing = new Date(data);
});
What was the purpose of multiplying the string by 1000? That operation doesn't make sense.
This PHP will work for that.
echo date('D, d M y H:i:s')." +0000";
date('D M d Y H:i:s O')
It won't work if your current locale isn't English.
A better alternative is to use:
new Date(<? echo date("Y, n - 1, d, H, i, s") ?>)
Here is an example with the DateTime object:
PHP code (works on PHP 5.3 or later)
$serverDate = new \DateTime('NOW');
// If you want to set a different time zone
// $serverDate = new \DateTime('NOW', new \DateTimeZone('Australia/Perth'));
echo $serverDate->format(DATE_ATOM);
JavaScript code
$.get('time.php', function(data) {
var serverDate = new Date(data);
});
A good way is timestamp:
echo $data = time()*1000;
echo '
<div id="setxDatetime">The current server time is: </div>
<script type="text/javascript">
var x = document.getElementById("setxDatetime");
x.innerHTML = x.innerHTML + new Date(' . $data . ');
</script>
';
1381324693000
The current server time is: Wed Oct 09 2013 16:18:13 GMT+0300 (GTB Standard Time)
There might be better solutions, but this one did the trick for me. The key issue is that JavaScript uses months 0-11, while PHP uses 1-12 as mentioned previously.
function convert_date_php_js($date) {
$converted_date = date("Y", strtotime($date)) . ', ' .
(date("n", strtotime($date))-1) . ', ' .
date("j", strtotime($date));
return $converted_date;
}
$priceDate = "2016-09-14";
$d = convert_date_php_js($priceDate);
// Returns 2016, 8, 14
It is very simple:
new Date("<?= date('Y/m/d H:i:s'); ?>");

How to turn php time function into javascript function?

I'm not that good at javascript (yet), so I need some help, with an alternative version of this php script (In javascript)
function until($format = ""){
$now = strtotime("now");
$nextTuesday = strtotime("-1 hour next tuesday");
$until = $nextTuesday - $now;
if(empty($format)){
return $until;
}else{
return date("$format",$until);
}
}
Just need it to count down, until next tuesday, in a really short way (Not in 20+ lines, like all the other script I've seen)
It should still return a timestamp, if it's possible (Need it for an offline app)
So if anyone could help me, I would be really happy (Not that I'm not happy right now, but I would be even happier) :D
You may want to take a look at the phpjs site. They have code showing how a substantial number of PHP functions can be done in JS.
Specifically: strtotime and date
JS doesn't have anything remotely close to strtotime. You'd have to determine "next tuesday" yourself. Once you've got that, you can extract a timestamp value using .getTime(), which will be the number of milliseconds since Jan 1/1970. This value can also be fed back into a new date object as a parameter, so you can do date math using simple numbers externally, then create a new date object again using the result.
e.g.
var now = new Date();
var ts = now.getTime();
var next_week = ts + (86400 * 7 * 1000);
next_week_object = new Date(next_week);
Once you've got the "next tuesday" code figured out, the rest is trivial
To get milliseconds till the next tuesday (nearest in the future):
function f_until(){
var now = new Date(Date.now());
var nextT = new Date(Date.now());
var cD = nextT.getDay();
if(cD < 2)nextT.setDate(nextT.getDate() + (2-cD));
else nextT.setDate(nextT.getDate() + (9-cD));
nextT.setHours(nextT.getHours() - 1);
//alert('next tuesday: '+nextT.toString());
return nextT.getTime() - now.getTime();
}

UTC Offset in PHP

What's the easiest way to get the UTC offset in PHP, relative to the current (system) timezone?
date('Z');
returns the UTC offset in seconds.
// will output something like +02:00 or -04:00
echo date('P');
timezone_offset_get()
$this_tz_str = date_default_timezone_get();
$this_tz = new DateTimeZone($this_tz_str);
$now = new DateTime("now", $this_tz);
$offset = $this_tz->getOffset($now);
Untested, but should work
I did a slightly modified version of what Oscar did.
date_default_timezone_set('America/New_York');
$utc_offset = date('Z') / 3600;
This gave me the offset from my timezone, EST, to UTC, in hours.
The value of $utc_offset was -4.
Simply you can do this:
//Object oriented style
function getUTCOffset_OOP($timezone)
{
$current = timezone_open($timezone);
$utcTime = new \DateTime('now', new \DateTimeZone('UTC'));
$offsetInSecs = $current->getOffset($utcTime);
$hoursAndSec = gmdate('H:i', abs($offsetInSecs));
return stripos($offsetInSecs, '-') === false ? "+{$hoursAndSec}" : "-{$hoursAndSec}";
}
//Procedural style
function getUTCOffset($timezone)
{
$current = timezone_open($timezone);
$utcTime = new \DateTime('now', new \DateTimeZone('UTC'));
$offsetInSecs = timezone_offset_get( $current, $utcTime);
$hoursAndSec = gmdate('H:i', abs($offsetInSecs));
return stripos($offsetInSecs, '-') === false ? "+{$hoursAndSec}" : "-{$hoursAndSec}";
}
$timezone = 'America/Mexico_City';
echo "Procedural style<br>";
echo getUTCOffset($timezone); //-06:00
echo "<br>";
echo "(UTC " . getUTCOffset($timezone) . ") " . $timezone; // (UTC -06:00) America/Mexico_City
echo "<br>--------------<br>";
echo "Object oriented style<br>";
echo getUTCOffset_OOP($timezone); //-06:00
echo "<br>";
echo "(UTC " . getUTCOffset_OOP($timezone) . ") " . $timezone; // (UTC -06:00) America/Mexico_City
This is same JavaScript date.getTimezoneOffset() function:
<?php
echo date('Z')/-60;
?>
This will output something formatted as: +0200 or -0400:
echo date('O');
This may be useful for a proper RSS RFC822 format
<pubDate>Sat, 07 Sep 2002 00:00:01 -0500</pubDate>
GMT offsets (like this) shouldn't use a colon (+02:00 from date('P');).
And, although it is acceptable for RSS RFC833, we don't want output like PDT and CST because these are arbitraty and "CST" can mean many things:
CST = Central Standard Time
CST = China Standard Time
CST = Cuba Standard Time
date("Z") will return the UTC offset relative to the server timezone not the user's machine timezone. To get the user's machine timezone you could use the javascript getTimezoneOffset() function which returns the time difference between UTC time and local time, in minutes.
<script type="text/javascript">
d = new Date();
window.location.href = "page.php?offset=" + d.getTimezoneOffset();
</script>
And in page.php which holds your php code, you can do whatever you want with that offset value. Or instead of redirecting to another page, you can send the offset value to your php script through Ajax, according to your needs.

Categories