I want to display two dates/times on my page
the server one, taken from the MySQL Server
the client one, taken from JavaScript
Since the output wasn't right, I started digging through my code and found something weird: I formatted the same timestamp in both php and javascript (see the code below) and the results differed by 3 hours.
timestamp: 1369855189
PHP:
var_dump( date( 'H:i:s', $timestamp ) );
Output: "19:19:49"
JavaScript:
dts = new Date( timestamp * 1000 );
var hours_s = dts.getHours();
var minutes_s = dts.getMinutes();
var seconds_s = dts.getSeconds();
current_server_time = hours_s + ":" + minutes_s + ":" + seconds_s";
Output: "22:19:49"
Does anyone know why this is happening? Does anyone know a workaround?
You and your server are probably not on the same timezome.
Try with javascript:
var hours_s = dts.getUTCHours();
var minutes_s = dts.getUTCMinutes();
var seconds_s = dts.getUTCSeconds();
The timestamp will be UTC...but once you put it into a PHP date object, it will have the timezone of the server. Once you put it into JavaScript, it will have the computer's local timezone. To set the timezone of the server in PHP, you can use this (replacing the timezone with yours) and see if that fixes it for you:
date_default_timezone_set('America/Chicago')
Obviously, to change the timezone for JavaScript requires changing your computer's timezone.
Is the php being executed in a server different from the machine where the JavaScript is parsed?
Either way, there is a workaround if you can work with gmt time:
Use the gmdate in your PHP script.
Use dts.getUTCHours() (and similar functions for the rest, prefixing UTC) in your JS. Check the ECMAScript standard p. 174. for more details.
If you want to work with local time, review the locale configuration of both server and client machines.
Related
My problem is as follows:
I want to display nepalese standard time in my website,so i set default timezone of my
website to 'Asia/kathmandu' using command: php_value date.timezone 'Asia/kathmandu' in htaccess file.
when i display time using any php functions like strftime() or date() ,it shows the nepalese standard time,
But when i use javascript function new Date(<?php echo time()*1000; ?>),it displays
the time of my personal pc i am using to view my website.
How can i display correct time using javascript date functions? Can anybody help me out?
Your issue is because javascript (actually ECMAScript) date objects are based on a UTC time value. When you do:
new Date(<?php echo time()*1000; ?>)
you are passing a UTC millisecond time value to the Date constructor, which then creates a date object. When you use the usual Date methods to format a string, or use Date.prototpye.toString or Date.prototype.toLocaleString, you will get a string based on the client's locale. Note that all these strings are implementation dependent and vary widely for the locale version.
If you want the timezone of the server, then use the server to set it. Or you can send a time zone offset in minutes to be applied to the local time to get back to Nepalese Standard Time (UTC + 5:45). Note that in ECMAScript, the time zone offset is minutes to be added to the local time to get UTC, whereas it is more normal to define the offset in minutes to be added to UTC to get the local time.
So to get NST:
function toNST(timeValue) {
function z(n) {return (n<10? '0' : '') + n}
var d = new Date();
var nstOffset = 5 * 60 + 45;
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + nstOffset);
return z(d.getHours()) + ':' + z(d.getMinutes()) + ':' + z(d.getSeconds());
}
alert(toNST(+(new Date()))); // about 11:07:17 at the moment
Use
new Date(Date.NPT(year, month, day, hour, minute, second))
Call the time via ajax from your server. That has the advantage of a better code maintanance. If you change the time again (e.g. if you want to use the code for another location) you have only to change the time in .haccess.
We are having problems to get the datetime representation in php and momentjs in sync. Lets say we are having a datetime with a time zone in Moscow:
2013-06-10T10:40:00.000+04:00
The user should see the time in local: 2013-06-10T10:40:00. No matter if he sits in Spain or USA. Following php code would produce the proper time that we need:
$date = new DateTime('2013-06-10T10:40:00.000+04:00');
echo $date->format('d.m.Y H:i:s');
The output is:
10.06.2013 10:40:00
But if we parse the same datetime string in frontend with momentjs:
moment('2013-06-10T10:40:00.000+04:00').format('D.M.YYYY h:mm:ss');
The output is:
10.6.2013 8:40:00
The browsers time zone is Europe/Berlin (+02:00). Using utc() calculates the date the wrong way also. What we need is a local time of the place, so in case of php it is the right one. Giving a parse string to momentjs:
moment('2013-06-10T10:40:00.000+04:00', "YYYY-MM-DD HH:mm").format('D.M.YYYY h:mm:ss')
would do the trick, so the time zone is deleted. But we actually should set the parse string globally, but how?
Thanks for suggestions.
I believe you are affected by moment.js issue 611 - which is actually a feature request, since JavaScript doesn't do this natively anyway. There is a somewhat acceptable workaround in the issue comments. Please add your own feedback there as well. Thanks.
UPDATE
With the release of moment.js version 2.1.0, you can now do this:
var input = "2013-06-10T10:40:00.000+04:00";
var m = moment(input).zone(input);
var s = m.format('D.M.YYYY h:mm:ss');
The extra call to .zone(input) will extract just the offset portion (+04:00) from the string and set it to the zone used for formatting. There are other options as well. See moment#zone in the docs.
UPDATE #2
With the release of moment.js version 2.3.0, this is now a single call:
var m = moment.parseZone(input);
Try setting the PHP timezone to Europe/Berlin
date_default_timezone_set("Europe/Berlin")
Might be your PHP installation/server is using a different timezone.
This is insane. How should I deal with it?
In Chrome console:
new Date(2013,0,1).getTime() // 1st of Jan 2013
> 1356991200000
------------
new Date(2013,0,1).getTime()== 1356991200000
> true
Now take that value in PHP:
<?php
die(date('l, j F Y'), 1356991200000 / 1000); // cut some ms
?>
I get Monday, 31 December 2012
Is this related to GMT? How do I fix this?
Javascript works with the timezone on the client whereas PHP works with the servers timezone.
JS: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset
var x = new Date()
var currentTimeZoneOffsetInHours = x.getTimezoneOffset()/60
PHP: http://php.net/manual/en/function.date-default-timezone-get.php
<?php
echo date_default_timezone_get();
Use either one (I would recommend server side). You can't relay that both will be in sync. One depends of your server and the other depends of the user's computer.
If you need to show something use relative time and update the client side time once the page refresh...
I have problem in comparing two dates. User will choose date from Datepicker with format ('Y-m-d'). If input is not equal to the current date then error message will showed up else output will be displayed.
I have this code:
$today = date("Y-m-d");
$date = $_REQUEST['selected_date']; // date selected
$first = strtotime($today);
$second = strtotime($date);
if ($first != $second){
//error message
}else{
//some code
}
This works fine in local but when i try to upload it, its not working anymore. Instead, the previous date can be accepted not the current date.
Probably the timezone is set differently on the server than from your local machine.
Try printing out the values of $first and $second.
You can (and should) set the timezone used by PHP with date_default_timezone_set() if you're using any of the old-style PHP date functions (date, strtotime etc).
Though I recommend using the DateTime & DateTimeZone classes with new code, they're nicer to work with, especially if you're doing anything involving multiple timezones.
Is there any possibility that the server is in a different time zone than where the request is coming from? I'd think this could lead to a mismatch.
Hopefully I understand your situation correctly. Attacking this directly will fail a lot of times because the server time zone (which you get through date()) will be different from the client time zone. To avoid this problem you need to send the client time to your server via javascript. jQuery example may look like this:
var date = new Date();
$.post("index.php", { today: (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear()}, function(data) {
alert(data); //server response here
});
on the server you get your client's today date as a string via $_POST['today']. Then you can decide what to do with it and output it to your client.
Alternatively, the problem you are describing can be solved just by JavaScript without sending it to your server unless you want to do something with it on your server
The server my PHP script is running on is set to UTC. I can't seem to figure out a way to set all dates to the browser's timezone. All dates displayed are formatted using PHP's date() function.
I know that via JavaScript's getTimezoneOffset() function, I can get the browser's current UTC offset (-4, in my case). How can I tell PHP to use this offset? I can use date_default_timezone_set(), but how do I convert an offset, say -4, to a time zone string, say America/New_York?
Note: The server is running PHP 5.1.6 (with no DateTime class) and I am using CodeIgniter.
As per the comment above- you could use a cookie...:
Javascript:
var today = new Date();
function SetCookie(cookieName,cookieValue,nDays) {
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString();
}
SetCookie("datecookie", today, 30);
window.location.href=window.location.href
PHP:
echo date("m d Y", strtotime($_COOKIE['datecookie']));
Because Javascript is client based and PHP is server based, they will not communicate. To tell the server the browser time, you will need to send information from the client, perhaps via Ajax, posting the browser time. The target PHP script should then handle/output this as appropriate. One other (obtuse) option is to attempt to geolocate the user based on IP, then guesstimate the correct time for that location- however this is inefficient for this purpose.
"I know I can use date_default_timezone_set(), but how do I convert an offset, say -4, to a time zone string, say America/New_York?"
Simply look at the comments associated with the documentation for that function. Comment #99006 does the work for you. You just need to get the timezone offset from the user.