/    Sign up×
Community /Pin to ProfileBookmark

Using JavaScript in PHP?

I am working on code to automatically detect a users timezone and then adjust the timestamps to reflect their timezone.

Here is a small JavaScript that will return the users current timezone.

[CODE]<script src=’http://code.jquery.com/jquery-2.1.1.js’></script>
<script src=”jstz.min.js”></script>
<script>
$(document).ready(function(){
var timezone = jstz.determine();

document.write(timezone.name());
});
</script>
[/CODE]

This will return for me “America/New_York”.

I need to somehow get the users timezone from this javascript and put it into a variable in PHP to be read by the script below.

[code=php]<?php

// Date & time format.
$date_format = “m/d/Y”;
$time_format = “h:i A”;

// Set timezone.
$timezone = “America/New_York”;

// Get current datetime.
$date = new DateTime();

// Set timezone.
$date->setTimezone(new DateTimeZone($timezone));

// Echo current date and time.
echo $date->format($date_format . ” ” . $time_format);

?>
[/code]

Can anyone help explain to me how I can do this?

to post a comment
PHP

5 Comments(s)

Copy linkTweet thisAlerts:
@ginerjmJul 23.2014 — Let your js code capture the value you want from some click event or even the form's submit event and store it into a hidden field contained by the same form. Now your just-selected value shows up in the form's action receiver as a $_POST variable. Bingo!!
Copy linkTweet thisAlerts:
@deathshadowJul 23.2014 — I'd actually store it in a cookie on pageload. That way it's available transparently in the background so you don't have to play with putting it in a form value.

In any of these cases though, you'd have to compensate for the fact the information will NEVER be available on your first load.... and the delay between it being sent and the offset being sent back. You could on every load send the current server time to the JS, so the JS can calculate the offset and put that into the cookie for use server-side or by the client-side scripting.

Also as a cookie, you could store it long term for later user visits.
Copy linkTweet thisAlerts:
@Strider64Jul 23.2014 — You could also do this via Ajax:

determingTimezone.php
[code=html]<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>TimeZone</title>
</head>

<body>
<p>Today's Date and Time is <span id="result"></span></p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="jstz.min.js"></script>
<script>
$(document).ready(function(){
var timezone = jstz.determine(),
myTimezone = timezone.name(), // Grab my Timezone:
params = { timezone: myTimezone }, // Create an object

/* A serialized repesentation of an object, suitable for an Ajax Request */
myData = jQuery.param( params );

/* The Ajax Request */
$.ajax({
type:"post",
url:"myDateScript.php",
data: myData, // The data that is being sent to myDateScript.php
success:function(info){
$('#result').html(info); // Display the result back when saved:
}
}); // End of Ajax Request:
}); // End of Doc Ready:
</script>
</body>
</html>[/code]


myDateScript.php
[code=php]<?php
// Date & time format.
$date_format = "m/d/Y";
$time_format = "h:i A";

// Set timezone.
$timezone = $_POST['timezone']; // The Ajax Request $_POST['timezone']:

// Get current datetime.
$date = new DateTime();

// Set timezone.
$date->setTimezone(new DateTimeZone($timezone));

// Echo current date and time... plus send the response back:
echo $date->format($date_format . " " . $time_format); [/code]


This way you load the timezone up in php when a user lands on your page and I like to see Deathshadow cringe (joking). ?
Copy linkTweet thisAlerts:
@deathshadowJul 23.2014 — The Ajax solution would really hinge on if you need it for scripting, or for PHP processing. I mean, there's no reason to ajax it otherwise.

Though I was thinking, if you had PHP send the server side time to the document, you could dhtml change any times on the page to reflect the difference. Store the UTC version of the 'element' time in the elements TITLE attribute like the microformat nutters would, then just go through and re-plug them in as content local time adjusted... since JS' Date() will automatically apply the local timezone.

Scripting off, just be sure the contents of those elements say UTC / GMT to be clear it's not showing local time.
Copy linkTweet thisAlerts:
@deathshadowJul 23.2014 — Yeah, check this:

Let's say you had PHP outputting markup like this:

&lt;div&gt;
&lt;h1&gt;Auto Date Conversion Script Test&lt;/h1&gt;
&lt;span class="convertTime"&gt;Wed Jul 23 2014 11:24:43 GMT-0000&lt;/span&gt;&lt;br /&gt;
&lt;span class="convertTime"&gt;Wed Jul 23 2014 11:24:43 GMT-1100&lt;/span&gt;&lt;br /&gt;
&lt;span class="convertTime"&gt;Wed Jul 23 2014 11:24:43 GMT-0200&lt;/span&gt;&lt;br /&gt;
&lt;span class="convertTime"&gt;Wed Jul 23 2014 8:24:43 GMT-0000&lt;/span&gt;
&lt;/div&gt;


and ran this script against it (place right before </body>)

(function(d) {

<i> </i>function classExists(e, className) {
<i> </i> return RegExp('(\s|^)' + className + '(\s|$)').test(e.className);
<i> </i>}

<i> </i>function textReplace(e, text) {
<i> </i> while (e.firstChild) e.removeChild(e.firstChild);
<i> </i> e.appendChild(d.createTextNode(text));
<i> </i>}

<i> </i>function textContent(e) {
<i> </i> return e.textContent || e.innerText;
<i> </i>}

<i> </i>var
<i> </i> spanList = d.getElementsByTagName('span'),
<i> </i> t, time;

<i> </i>for (t = 0; t &lt; spanList.length; t++) if (
<i> </i> classExists(spanList[t], 'convertTime')
<i> </i>) textReplace(spanList[t], new Date(textContent(spanList[t])).toString());

})(document);


The end result would be:

Auto Date Conversion Script Test

Wed Jul 23 2014 07:24:43 GMT-0400

Wed Jul 23 2014 18:24:43 GMT-0400

Wed Jul 23 2014 09:24:43 GMT-0400

Wed Jul 23 2014 04:24:43 GMT-0400

If you are in EST with daylight savings. It's just a simple demo, but it shows you how to easily do postprocessing of the data.

If you wanted a simpler time output, you could put the formatted full version into TITLE like the microformats guys used to, and have the content of the tag be 'simpler'.
×

Success!

Help @c_nickerson spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...