Solved

Time difference

Posted on 2016-11-08
10
52 Views
Last Modified: 2016-11-09
Hi I asked this question before, thought I had a working solution, but I'm back again. I have two time inputes, and want to be able to display the difference between the two on the form on a button click. the two text boxes are starttime1 and endtime1, and on a button click I want to display the time passed in a separate text box. How can I go about this?
0
Comment
Question by:peter Ojeda
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
  • 2
10 Comments
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 41879022
Do you want to do this in PHP?  If so, these articles show ways of doing date/time arithmetic.

Procedural
https://www.experts-exchange.com/articles/201/Handling-Date-and-Time-in-PHP-and-MySQL-Procedural-Version.html

Object-oriented
https://www.experts-exchange.com/articles/20920/Handling-Time-and-Date-in-PHP-and-MySQL-OOP-Version.html

If you want to do this on the client-side (in the browser without reference to PHP) you might use "Request attention" and ask a moderator to add the question to the JavaScript Zone.
0
 
LVL 58

Assisted Solution

by:Julian Hansen
Julian Hansen earned 500 total points
ID: 41879373
This is not a PHP solution and you did not state how you want the difference represented but here is a shot at a client side JavaScript / jQuery solution.
	Start Time <input type="text" name="starttime1" id="starttime1" />
	End Time <input  type="text" name="endtime1" id="endtime1"/>
	Difference <input type="text" name="difference" readonly id="difference"/>
	<br/>
	<button class="calculate btn btn-primary">Calculate</button>

Open in new window

jQuery
<script>
$(function() {
  $('.calculate').click(function() {
    var starttime1 = new Date ($('#starttime1').val());
    var endtime1 = new Date($('#endtime1').val());

    var diff = endtime1.getTime() - starttime1.getTime();
    $('#difference').val(diff);
  });
})
</script>

Open in new window

Working sample here
1
 
LVL 1

Author Comment

by:peter Ojeda
ID: 41879375
Hi sorry you are right I forgot to add that part. I am attempting to find the number of minutes passed from start time to end time.
0
Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

 
LVL 110

Expert Comment

by:Ray Paseur
ID: 41879429
Here's a PHP solution.  We create a user-defined function to compute the elapsed minutes between any two valid Date/Time strings.

Supported formats for Date/Time strings are here: http://php.net/manual/en/datetime.formats.php
<?php // demo/temp_ojeda.php
/**
 * https://www.experts-exchange.com/questions/28981779/Time-difference.html
 *
 * https://www.experts-exchange.com/articles/20920/Handling-Time-and-Date-in-PHP-and-MySQL-OOP-Version.html
 * Note: UTC does not observe daylight savings time, so the elapsed computations will be correct throughout the year.
 */
error_reporting(E_ALL);
echo '<pre>';


// DEFINE A FUNCTION TO COMPUTE ELAPSED MINUTES
function elapsed_minutes($alpha, $omega, $zone='UTC')
{
    try
    {
        $tzone      = new DateTimeZone($zone);
        $date_alpha = new DateTime($alpha, $tzone);
        $date_omega = new DateTime($omega, $tzone);
    }
    catch(Exception $e)
    {
        trigger_error($e->getMessage(), E_USER_WARNING);
        return FALSE;
    }
    $elapsed = (int)round( ( $date_omega->format('U') - $date_alpha->format('U') ) / 60);
    return $elapsed;
}


// USE THE FUNCTION
$alpha = "2:30:47pm";
$omega = "3:43:12pm";
var_dump( elapsed_minutes($alpha, $omega) );

$alpha = "Yesterday 2:30:47pm";
$omega = "3:43:12pm";
var_dump( elapsed_minutes($alpha, $omega) );

Open in new window

0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 41879509
This may be a little better.  It's a two-step solution.  Using AJAX you can get the expressive power of the PHP supported date/time strings without having to write a lot of JavaScript code.  You may want to add some sanity checks to this, but it seems to work OK if it's given useful inputs.

Test here: https://iconoun.com/demo/temp_peter_ojeda_client.php

Server-side script:
<?php // demo/temp_peter_ojeda_server.php
/**
 * https://www.experts-exchange.com/questions/28981779/Time-difference.html
 *
 * https://www.experts-exchange.com/articles/20920/Handling-Time-and-Date-in-PHP-and-MySQL-OOP-Version.html
 * Note: UTC does not observe daylight savings time, so the elapsed computations will be correct throughout the year.
 */
error_reporting(E_ALL);


// DEFINE A FUNCTION TO COMPUTE ELAPSED MINUTES
function elapsed_minutes($alpha, $omega, $zone='UTC')
{
    try
    {
        $tzone      = new DateTimeZone($zone);
        $date_alpha = new DateTime($alpha, $tzone);
        $date_omega = new DateTime($omega, $tzone);
    }
    catch(Exception $e)
    {
        return $e->getMessage();
    }
    $elapsed = (int)round( ( $date_omega->format('U') - $date_alpha->format('U') ) / 60);
    return $elapsed;
}


// USE THE FUNCTION
echo elapsed_minutes( $_GET['alpha'], $_GET['omega'] );

Open in new window

Client-side script:
<?php // demo/temp_peter_ojeda_client.php
/**
 * https://www.experts-exchange.com/questions/28981779/Time-difference.html
 */
error_reporting(E_ALL);


// CREATE OUR WEB PAGE IN HTML5 FORMAT, USING HEREDOC SYNTAX
$htm = <<<HTML5
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<style type="text/css">
/* STYLE SHEET HERE */
</style>

<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
    $("#go").click(function(){
        var alpha = $("input[name=alpha]").val();
        var omega = $("input[name=omega]").val();
        $.get("temp_peter_ojeda_server.php", {alpha:alpha, omega:omega}, function(resp){
            $("input[name=lapse]").val(resp)
        });
    });
});
</script>

<title>HTML5 Page With jQuery in UTF-8 Encoding</title>
</head>
<body>

<noscript>Your browsing experience will be much better with JavaScript enabled!</noscript>

<p>Enter Start and End date/time strings, then <input id="go" type="button" value="click here" />
<br>
Start: <input name="alpha" /> End: <input name="omega" /> Elapsed Minutes: <input name="lapse" readonly />
</p>
</body>
</html>
HTML5;


// RENDER THE WEB PAGE
echo $htm;

Open in new window

HTH, ~Ray
0
 
LVL 58

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 41879912
Can you confirm if you are interested in a PHP (server side soution) or JavaScript / jQuery (client side solution)
Minutes
HTML
    <form action="reflect.php" method="post">
      Start Time <input type="text" name="starttime1" id="starttime1" />
      End Time <input  type="text" name="endtime1" id="endtime1"/>
      Difference (ms) <input type="text" name="milliseconds" readonly id="milliseconds"/>
      Difference (min) <input type="text" name="minutes" readonly id="minutes"/>
      <br/>
      <button class="calculate btn btn-primary">Calculate</button>
	  <button class="btn btn-primary" type="submit">Submit</button>
  </form>

Open in new window

jQuery
<script>
$(function() {
  $('.calculate').click(function(e) {
    e.preventDefault();
    var starttime1 = new Date ($('#starttime1').val());
    var endtime1 = new Date($('#endtime1').val());

	
    var ms = (endtime1.getTime() - starttime1.getTime());
	var minutes = ms / 60000
    $('#milliseconds').val(ms);
    $('#minutes').val(minutes);
  });
})
</script>

Open in new window

Updated sample here
0
 
LVL 58

Assisted Solution

by:Julian Hansen
Julian Hansen earned 500 total points
ID: 41879914
Using AJAX you can get the expressive power of the PHP supported date/time strings without having to write a lot of JavaScript code.
That's why we have libraries like MomentJs http://momentjs.com/
2
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 41880409
@Julian: That's a good idea, but I don't know enough MomentJS to produce a practical solution with a code sample!
1
 
LVL 1

Author Comment

by:peter Ojeda
ID: 41880459
Thankyou Julian MomentJs looks very helpful I will look more into that.
0
 
LVL 58

Expert Comment

by:Julian Hansen
ID: 41880834
You are welcome.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question