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.
Related
For example -
In Jquery using the function (new Date()).getTime() am getting current datetime as 1470291303352.
But In PHP using strtotime(date('H:i:s')) am getting it as 1470291299.
Here i need to get the same string values. How to do it?
Firstly, php returns the number of seconds since 1970/01/01, jquery returns a number of milliseconds, so there is no way to be the same value.
Second - even if you've got the fastest server in the world it comes to the milliseconds in the execution of lines of code. So exactly the same value can hardly be achieved :)
What you can do to try to trim jquery for the last three numbers representing the milliseconds (this of course if you do these two lines of code to execute in one second :))
And for last, there is a issue of clocks on your server and client computer - it must be exactly the same.
The javascript method getTime() returns microseconds (http://www.w3schools.com/jsref/jsref_gettime.asp) whereas PHP time() (or in your case strtotime() http://php.net/manual/en/function.strtotime.php) returns seconds. The first depends on your clients clock, the latter on your servers clock...
Mostly you never will get the same timestamps this way... maybe you could work around using some kind of AJAX api to have the same timestamp on both sides...
Check this :
In php:
echo strtotime(date('H:i:s')); // 1470294647
In Script :
var date = new Date();
var d = Date.parse("'"+date+"'")/1000; // 1470294647
alert(d);
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.
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.
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