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...
Related
When I write this line of code on local, the output will be this:
echo time(); // 1464605083
And when I write in on the 3v4l (online PHP shell) the output will be this:
echo time(); // 1339412843
As you see there is a huge different between those outputs. What's wrong? And how can I sync them?
Note: I'm using Xampp on my local.
If the time you got back from the code is not the right time, it's probably because your server is in another country or set up for a different timezone.
So, if you need the time to be correct according to a specific location, you can set a timezone to use.
The example below sets the timezone to "America/New_York", then outputs the current time in the specified format:
<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>
That timezone will be vary according to the servers you are using. If you want to use same timezone in all your server. Use
date_default_timezone_set('timezonename')
use timezone i hope it's work ...
<?php
date_default_timezone_set('America/New_York');
echo $date= time() ;
?>
The webserver where you are testing this has a completely off system time set.
If you look at the date of your test script (right next to the title field) you'll see that it has been saved at # Mon Jun 11 2012 11:07:23.
Your timestamp 1339412843 translates to 06/11/2012 # 11:07am (UTC).
So, the server time is just wrong. Test your script someplace else if time is critical.
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.
When I add this to the code
$today1 = date("d");
it gives me the server date and not the user local system date.
I do not want to use date_default_timezone_set()
How can I get the date of the local user(not web host server) at that point of time using PHP.
PHP runs on the server so using functions like time() and localtime() will not get you the time of the client.
Javascript runs on client's system thus it can get the time of the client. But how to make the time available to a PHP script is a tricky part.
The answer is AJAX Request, you can send the time from ajax to you script file which will use that value and give you results.
Like
var clientTime = Date.now();
$.get("yourpage.php", { time: clientTime }, function(data)
// the response in data
});
You are not able to do that unless default timezone function. PHP is server side not client side. You may need to use javascript for that -
var now = new Date();
now.format("m/dd/yy");
// Returns, e.g., 6/09/07
// Can also be used as a standalone function
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM
// You can use one of several named masks
now.format("isoDateTime");
// 2007-06-09T17:46:21
// ...Or add your own
dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
now.format("hammerTime");
// 17:46! Can't touch this!
// When using the standalone dateFormat function,
// you can also provide the date as a string
dateFormat("Jun 9 2007", "fullDate");
// Saturday, June 9, 2007
// Note that if you don't include the mask argument,
// dateFormat.masks.default is used
now.format();
// Sat Jun 09 2007 17:46:21
// And if you don't include the date argument,
// the current date and time is used
dateFormat();
// Sat Jun 09 2007 17:46:22
// You can also skip the date argument (as long as your mask doesn't
// contain any numbers), in which case the current date/time is used
dateFormat("longTime");
// 5:46:22 PM EST
// And finally, you can convert local time to UTC time. Either pass in
// true as an additional argument (no argument skipping allowed in this case):
dateFormat(now, "longTime", true);
now.format("longTime", true);
// Both lines return, e.g., 10:46:21 PM UTC
// ...Or add the prefix "UTC:" to your mask.
now.format("UTC:h:MM:ss TT Z");
// 10:46:21 PM UTC
or try this - https://bitbucket.org/pellepim/jstimezonedetect
How to pass Javascript variable to PHP?
Simply send the date time value to a PHP file using AJAX. Its easy and you can use jQuery for that. Then set cookies/session. That's it!
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.
Is it possible to have JavaScript compute a timestamp returned from PHP's time() function and present it in a readable format such as "Sun, 18th April 2010 at 4:00 pm"?
Use the Date object to do that:
new Date(<?php echo time(); ?>*1000)
You need to multiply the Unix timestamp by 1000 becuase Date expects the timestamp to be in milliseconds.
And to format the date, you can use this Date.format method (Date has none built in).
You're going to want to be really careful doing this stuff. When you take a server-side time value that's a traditional "number of seconds (or milliseconds) since the Epoch boundary" value, and then turn that into some sort of "Date" object, well a translation occurs into the time zone appropriate to the locale of the context.
The problem arises when you've got a server located in Chicago, and somebody in Hawaii using your site, say after a party — one of those "luau" affairs, no doubt, complete with roasted pig and grass-skirted dancing girls, a rare evening under warm tropical skies, exotic flowers scenting the ocean breezes — and it's late now. My goodness, it's almost midnight! Whatever will mother think when I write her about the party?
Our party-goer sits down at 11:30 PM to use your site. Now, of course, being considerably east of Hawaii, your server thinks it's 5:30AM, and the date is one day later than the date our party-goer will jot down in his quick note to Mom. So your server writes its time value into a web page as described in the answers here, and — correctly — the local Hawaii time shows up on the page in our party-goer's hotel room.
The problem is this: if that local time makes it back to your application from some form field, and your application treats it as local time in Chicago, then your site will get yesterday's date. Depending on your application that's either OK or it's not OK - the point is, you have to keep track of where a date (expressed in ordinary calendar notation) comes from vis-a-vis where the date is used.
You can of course have the opposite problem. That is, if your server always renders dates in its local time zone, then users elsewhere in the world will see confusing (apparently wrong) date and time values, so the interface has to make clear what those values mean. The issues become important when your site provides services involving schedules. If it's possible to schedule operations, it's important that the interface keeps things on the level so that "April 30th at 10:00PM" means either that date and time at the server or that date and time in the locale from which the schedule was arranged. Whichever it is, you have to be careful to keep things consistent.
Instead of a numeric unix timestamp you can also send a textual representation of the date that Date.parse() understands.
Maybe it's just my contribution to global warming but I think there are benefits in using a format that is a bit more human readable and contains the timezone info.
e.g.
<?php
// I have "decided" America/Los_Angeles fits most of my audience
date_default_timezone_set('America/Los_Angeles');
$now = time();
$yesterday = strtotime('yesterday', $now);
// March 27, 1976 08:00:00 tz:America/Los_Angeles
$someotherdate = mktime(8, 0, 0, 3, 27, 1976)
?><html>
<head><title>...</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function foo() {
$('.datetime').each( function() {
var t = $(this).text();
t = new Date(Date.parse(t)).toLocaleString();
$(this).text(t);
});
}
</script>
</head>
<body>
<div><span class="datetime"><?php echo date(DateTime::RSS, $now); ?></span></div>
<div><span class="datetime"><?php echo date(DateTime::RSS, $yesterday); ?></span></div>
<div><span class="datetime"><?php echo date(DateTime::RSS, $someotherdate); ?></span></div>
<button onclick="foo()">to local time</button>
</body>
</html>
This prints
Sat, 17 Apr 2010 04:40:15 -0700
Fri, 16 Apr 2010 00:00:00 -0700
Sat, 27 Mar 1976 08:00:00 -0800
in my browser and (since my local timezone is Europe/Berlin, CET, UTC+1/2) after hitting the to local time button
Samstag, 17. April 2010 13:40:15
Freitag, 16. April 2010 09:00:00
Samstag, 27. März 1976 17:00:00
It's now 2013, and as more and more people switch from processing SQL results on PHP side to passing results in JSON and processing on client side, I think moment.js deserves some attention of its own for offering easy replacements to PHP's strtotime() and date() functions in Javascript, plus some more.
Just include:
<script src="SCRIPT_DIR/moment.min.js" type="text/javascript"></script>
Then it's as easy as:
// Simulates ajax response
var data = { someDate: "2023-08-23 11:52:39" }
// .unix() converts to Unix timestamp: 1692816759
moment(data.someDate).unix();
// Displaying it in a readable format
// Aug 23, 11:52 AM
moment("2023-08-23 11:52:39").format('MMM D, hh:mm A');
// Now
moment();
// Support for manipulation and chaining
moment().add('days', 7).subtract('months', 1).hours(15).minutes(0).seconds(0);
You can get the 5.5kb js file here:
http://momentjs.com/
More docs here:
http://momentjs.com/docs/