Results 1 to 6 of 6

Thread: Using JavaScript in PHP?

  1. #1
    Join Date
    Jun 2014

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

    <script src='http://code.jquery.com/jquery-2.1.1.js'></script>
    <script src="jstz.min.js"></script>
     var timezone = jstz.determine();
    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.

    PHP Code:

    // 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);

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

  2. #2
    Join Date
    Jul 2013
    Voorheesville NY USA
    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!!
    PS - If you're posting here you should be using:

    ini_set('display_errors', '1');

    at the top of ALL php code while you develop it!

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

  4. #4
    Join Date
    Feb 2013
    You could also do this via Ajax:

    HTML Code:
    	<meta charset="utf-8">
    	<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>
    			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 */		
    				data: myData, // The data that is being sent to myDateScript.php
    					$('#result').html(info); // Display the result back when saved: 
    			}); // End of Ajax Request:				
    		}); // End of Doc Ready:
    PHP Code:
    // 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);
    This way you load the timezone up in php when a user lands on your page and I like to see Deathshadow cringe (joking).
    Last edited by Strider64; 07-23-2014 at 08:50 AM.

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

  6. #6
    Yeah, check this:

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

    	<h1>Auto Date Conversion Script Test</h1>
    	<span class="convertTime">Wed Jul 23 2014 11:24:43 GMT-0000</span><br />
    	<span class="convertTime">Wed Jul 23 2014 11:24:43 GMT-1100</span><br />
    	<span class="convertTime">Wed Jul 23 2014 11:24:43 GMT-0200</span><br />
    	<span class="convertTime">Wed Jul 23 2014 8:24:43 GMT-0000</span>
    and ran this script against it (place right before </body>)

    (function(d) {
    	function classExists(e, className) {
    		return RegExp('(\\s|^)' + className + '(\\s|$)').test(e.className);
    	function textReplace(e, text) {
    		while (e.firstChild) e.removeChild(e.firstChild);
    	function textContent(e) {
    		return e.textContent || e.innerText;
    		spanList = d.getElementsByTagName('span'),
    		t, time;
    	for (t = 0; t < spanList.length; t++) if (
    		classExists(spanList[t], 'convertTime')
    	) textReplace(spanList[t], new Date(textContent(spanList[t])).toString());
    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'.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center