Date of user local-system not hosted server - PHP - php

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!

Related

How to show a Unix-time in a local time format

I have a php variable say $expTime (which has a unixtime say-1359683953) . I want to display this variable on the client side(in a proper time format according to his local time) . I am so confused between the UTC ,GMT , DST all that things. Can anyone suggest a solution for this using php or javascript please.
when I am using echo date('h:i M d/y',$expTime) it is showing me a wrong time.
How I am saving the time to database:
var exp_day= parseInt($("#exp_day").val());
var exp_hrs= parseInt($("#exp_hrs").val());
var exp_min= parseInt($("#exp_min").val());
var exp_time = (exp_day*24*60*60) + (exp_hrs*60*60) + (exp_min*60) ;
then I posted the exp_time using ajax to a php file -
$expTime = time() + $_POST["exp_time"];
What I am retrieving from the database is $expTime . This $expTime I want to display it on the all the clients system according to there local time zone (also by making sure the day light saving)
Use DateTime with timezones:
$datetime = new DateTime('#1359683953');
echo $datetime->format('h:i M d/y') . "<br>";
$datetime->setTimezone(new DateTimeZone('America/Los_Angeles'));
echo $datetime->format('h:i M d/y');
See it in action
UNIX time values are usually UTC seconds since epoch. Javascript time values are UTC milliseconds since the same epoch. The ECMA-262 Date.prototype.toString method automatically generates a string representing the local time and takes account of daylight saving if it applies.
You can also use Date methods to create your own formatted string, they also return local time and date values. There are also UTC methods if you want to work in UTC.
To do this on the client, just provide a UTC time value from the server and then all you need in javascript is:
var timeValue = 1359683953; // assume seconds
var date = new Date(timeValue * 1000); // convert time value to milliseconds
alert(date); // Fri 01 Feb 2013 11:59:13 GMT+1000

Discrepancy between PHP and JS's timestamps

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...

Updating Time in Local Storage

I am trying to connect to the server every minute and pass in the variable of the current time, which would be the lastUpdate. On the server side php file, I plan to compare the passed in time variable with a TIMESTAMP in the database rows; much like if (time1-time2 > certain value)... So far the javascript code is:
var time;
var timer_is_on = 0;
localStorage.lastUpdate = 0;
localStorage.numUpdates = 0;
function timedCount()
{
localStorage.lastUpdate = new Date();
//connect to server
contactServer(localStorage.lastUpdate);
currentCount=currentCount+1;
time=setTimeout("timedCount()",60000);
}
My question is whether I am doing this correctly. I am declaring localStorage.lastUpdate as new Date() and I'm not sure whether this is correct? I have tried the loop and every minute lastUpdate seems to be the same date and time.
My last question is whether I can actually compare the two time formats from javascript and php. In the SQL timestamp, the format is 2012-03-20 11:14:40 while the date format from the javascript new Date() is Tue Mar 20 2012 12:32:44 GMT-0400 (Eastern Daylight Time).
Any information would be helpful, thanks!
Be careful when you use time. Your server time may be different from your client time. The best for you is to store the date of the last request in $_SESSION['last'].
With this solution, all your problems are not anymore. Your PHP set the date, so it is the same reference, and it's in a good format.
Just keep your timeout on the client side:-)
Use new Date().getTime() to return a UNIX timestamp; that is, the number of seconds since Jan 1st, 1970. This makes it much easier to compare with other times.
localStorage.lastUpdate = new Date().getTime();
Will return something like this: 1332266002.
The PHP equivalent is simply time().
And to convert that UNIX timestmap into a MySQL TIMESTAMP, use MySQL's FROM_UNIXTIME function.

Convert all dates in PHP to local time

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.

JavaScript readable date/time from PHP's time()

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/

Categories