Jump to content

Recommended Posts

Hi.

 

Need some help on one simple task yet so hard. I have puzzled on this for days and no luck. I have a great script i got from somewhere.

 

function get_time_difference( $start, $end )
{
    $uts['start']      =    strtotime( $start );
    $uts['end']        =    strtotime( $end );
    if( $uts['start']!==-1 && $uts['end']!==-1 )
    {
        if( $uts['end'] >= $uts['start'] )
        {
            $diff    =    $uts['end'] - $uts['start'];
            if( $days=intval((floor($diff/86400))) )
                $diff = $diff % 86400;
            if( $hours=intval((floor($diff/3600))) )
                $diff = $diff % 3600;
            if( $minutes=intval((floor($diff/60))) )
                $diff = $diff % 60;
            $diff    =    intval( $diff );            
            return( array('days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
        }
        else
        {
            trigger_error( "Ending date/time is earlier than the start date/time", E_USER_WARNING );
        }
    }
    else
    {
        trigger_error( "Invalid date/time data detected", E_USER_WARNING );
    }
    return( false );
}

 

Now the other part is that i have 3 textboxes and i woul like to add the first one like 15:00:00 the second one 18:30:00 and the third would display the difference in

lets say seconds. At least the function displays the results in seconds. But the problem is how to get the textbox to work whitout posting the info but to use onchange

 

Any ideas?

	<input type="text" value="" name="start_time"/>
<input type="text" value="" name="end_time"/>
<input type="text" value="______" name="difference"/>

 

If you are trying to do it through PHP only, you cannot achieve what you are trying here. You need to take JavaScript to do the asynchronous calculation of the time diff. Here is a rough implementation that you are trying.

 

HTML code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    $("#end_time").blur(function(){
      $("#message").text("Calculating. Wait...");
      var start_time = $("#start_time").val();
      var end_time = $("#end_time").val();
      $.getJSON("test.php?s="+start_time+"&e="+end_time, function(data){
        var success = data.success;
        if (success == 1) {
          $("#message").text("Calculation done! See result below.");
          $("#difference").val(data.days + " day(s) " + data.hours + " hour(s) " + data.minutes + " minute(s) " + data.seconds + " second(s) ");
        }
        else {
          $("#message").text("Error! " + data.reason);
        }
      })
    });
  });

</script>
</head>
<body>
  <div id="message"> </div>
  <form>
    <input id="start_time" type="text" value="" name="start_time"/>
    <input id="end_time" type="text" value="" name="end_time"/>
    <input id="difference" type="text" value="" name="difference"/>
  </form>
</body>
</html>

 

And the time calculation script (test.php here, you can change it as per the filename that you have):

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set("log_errors", 0);

function get_time_difference( $start, $end )
{
  $uts['start']      =    strtotime( $start );
  $uts['end']        =    strtotime( $end );
  if( $uts['start']!==-1 && $uts['end']!==-1 )
  {
    if( $uts['end'] >= $uts['start'] )
    {
      $diff    =    $uts['end'] - $uts['start'];
      if( $days=intval((floor($diff/86400))) )
      $diff = $diff % 86400;
      if( $hours=intval((floor($diff/3600))) )
      $diff = $diff % 3600;
      if( $minutes=intval((floor($diff/60))) )
      $diff = $diff % 60;
      $diff    =    intval( $diff );
      return( array('success'=>1, 'days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
    }
    else
    {
      return(array('success'=>0, 'reason'=>'Ending date/time is earlier than the start date/time'));
      //trigger_error( "Ending date/time is earlier than the start date/time", E_USER_WARNING );
    }
  }
  else
  {
    return(array('success'=>0, 'reason'=>'Invalid date/time data detected'));
    //trigger_error( "Invalid date/time data detected", E_USER_WARNING );
  }
}

$start = $_GET['s'];
$end = $_GET['e'];

echo json_encode(get_time_difference( $start, $end ));
?>

 

You can always refine the output that you need to do in the JavaScript area.

 

Hope this helps.

That's a bit long winded code. I would have done this with select lists. Here's my version:

 

index.php

<?php
function time_counter($max, $step = 1) {
for($x = 0; $x <= $max; $x++) {
	if(!($x%$step)) {
		$array[] = (strlen($x) == 1) ? str_pad($x,2,'0',STR_PAD_LEFT) : $x;
	}
}
return $array;
}

$hours = time_counter(23);
$mins_and_secs = time_counter(59);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<style type="text/css">
body, select { font-family: verdana; font-size: 12px; }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('select').change(function() {
	timediff();
});

function timediff() {
	var required = 6;
	var selected = 0
	$('select option:selected').each(function() {
		if($(this).text()) {
			selected++;	
		}
	});
	if(selected == required) {
		start = $('#starthr option:selected').text()+':'+$('#startmin option:selected').text()+':'+$('#startsec option:selected').text();
		end = $('#endhr option:selected').text()+':'+$('#endmin option:selected').text()+':'+$('#endsec option:selected').text();
		/*
		call the php function
		*/
		ajax_url = 'test.php?action=calculate&start='+start+'&end='+end;
		$('div#output').load(ajax_url);
	}		
}
});
</script>
</head>
<body>
<div id="options">
<p>start time: 
<select name="starthr" id="starthr">
<option value=""></option>
<?php foreach($hours as $hour) { ?><option value="<?php print $hour; ?>"><?php print $hour; ?></option><?php } ?>
</select> : 
<select name="startmin" id="startmin">
<option value=""></option>
<?php foreach($mins_and_secs as $min) { ?><option value="<?php print $min; ?>"><?php print $min; ?></option><?php } ?>
</select> :
<select name="startsec" id="startsec">
<option value=""></option>
<?php foreach($mins_and_secs as $sec) { ?><option value="<?php print $sec; ?>"><?php print $sec; ?></option><?php } ?>
</select>
 
end time: 
<select name="endhr" id="endhr">
<option value=""></option>
<?php foreach($hours as $hour) { ?><option value="<?php print $hour; ?>"><?php print $hour; ?></option><?php } ?>
</select> : 
<select name="endmin" id="endmin">
<option value=""></option>
<?php foreach($mins_and_secs as $min) { ?><option value="<?php print $min; ?>"><?php print $min; ?></option><?php } ?>
</select> : 
<select name="endsec" id="endsec">
<option value=""></option>
<?php foreach($mins_and_secs as $sec) { ?><option value="<?php print $sec; ?>"><?php print $sec; ?></option><?php } ?>
</select>
</p>
</div>

<div id="output"></div>
</body>
</html>

 

test.php

<?php
function time_diff($start, $end) {
$start = strtotime($start);	
$end = strtotime($end);	
$diff = $end - $start;
return $diff;
}
if(isset($_GET['action']) && $_GET['action'] == 'calculate') {
print 'The difference in seconds between the two times is: '.time_diff($_GET['start'], $_GET['end']);
}
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.