Solved

Time Difference Two Dates php

Posted on 2010-11-09
30
377 Views
Last Modified: 2012-05-10
I know there are a ton of time difference docs out there and I have looked through the net for what I need and cant find it, Im not saying I have looked through everything but what I am looking for I have not found. My timestamp is in this format

$start = date("1899-12-30 h:i:s"); This is my current time, I know its not 1899 but thats the date the db I am accessing uses. Why ? I have no idea but all I care about is the h:i:s part of it

$end = date("1899-12-30 10:00:00"); This is my end time, again the 1899 thing. All I want from it is the time difference in minutes. Can someone point me to the right place :)
0
Comment
Question by:cbielich
  • 13
  • 12
  • 3
  • +2
30 Comments
 
LVL 1

Expert Comment

by:MountMann
Comment Utility
you can use strtotime to convert it to numbers, and then calculate with it. See the attached file for an example.
<?php



// For example:



$date1 = "2008-03-24"; 

$date2 = "2009-06-26"; 

 

$diff = abs(strtotime($date2) - strtotime($date1)); 

 

$years = floor($diff / (365*60*60*24)); 

$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24)); 

$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24)); 

 

printf("%d years, %d months, %d days\n", $years, $months, $days); 

?>

Open in new window

0
 
LVL 1

Author Comment

by:cbielich
Comment Utility
I mentioned that the format I am using was date("1899-12-30 h:i:s") and that I needed time difference in minutes. I tried your code and all I get is 0 for years, months and days
0
 
LVL 6

Expert Comment

by:stilliard
Comment Utility
PHP5 has a great class for handling DateTime.
You may find something on here:
http://www.php.net/manual/en/datetime.diff.php
0
 
LVL 10

Expert Comment

by:TRW-Consulting
Comment Utility
Is "h:i:s" literal?  Or is this replaced with numbers for hour, minute, and second.  (how does 'i' correspond to minute?)

If you want better and faster answers, supply actual data you want to work with, and a sample of the actual results you want.
0
 
LVL 1

Author Comment

by:cbielich
Comment Utility
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility

<?php // RAY_temp_1899.php

error_reporting(E_ALL);



// MAN PAGE http://us.php.net/manual/en/datetime.gettimestamp.php



// REQUIRED FOR PHP 5.1+

date_default_timezone_set('America/Chicago');



// FROM THE POST AT EE

$start = date("1899-12-30 h:i:s");

$end = date("1899-12-30 10:00:00");



// A LITTLE BETTER EXAMPLE

$start = "1899-12-30 h:i:s";

$end   = "1899-12-30 10:00:00";



// AVOID THE STACK TRACE - REMOVE THE USELESS CHARACTERS

$start = preg_replace('/[^0-9 ]/', '', $start);



// SEE WHAT WE GOT

echo "<pre>";

$s = new DateTime($start);

var_dump($s);

$e = new DateTime($end);

var_dump($e);



// GET UNSIGNED TIMESTAMP NUMBERS SO WE CAN DO MATH

$sts = $s->format('U');

$ets = $e->format('U');

$dif = $ets - $sts;

var_dump($dif);



// TIMESTAMP IS SECONDS - GET THE DIFFERENCE IN MINUTES

$min = $dif / 60;

$min = (int)$min;

echo PHP_EOL . "$min MINUTES";

Open in new window

0
 
LVL 1

Author Comment

by:cbielich
Comment Utility
Im getting, looks like it does not like ":"

Fatal error:  Uncaught exception 'Exception' with message 'DateTime::__construct() [<a href='function.DateTime---construct'>function.DateTime---construct</a>]: Failed to parse time string (1899-12-30 h:i:s) at position 12 (:): Unexpected character' in /var/www/sd/clockin/test.php:34
Stack trace:
#0 /var/www/sd/clockin/test.php(34): DateTime->__construct('1899-12-30 h:i:...')
#1 {main}
0
 
LVL 1

Author Comment

by:cbielich
Comment Utility
Here is all my code
<? include ('includes/connect.php'); ?>
<?
$today = date('Y-m-d') . " 00:00:00";
$sql = "SELECT * FROM `daycare attendance table` WHERE Date = '$today' AND StudentID = 'KB009' AND EndTime IS NULL";
$result = mysql_db_query($db,$sql,$cid);
$records = mysql_num_rows($result);
while($row = mysql_fetch_array($result)) {
extract($row);	
}

// RAY_temp_1899.php
error_reporting(E_ALL);

// MAN PAGE http://us.php.net/manual/en/datetime.gettimestamp.php

// REQUIRED FOR PHP 5.1+
date_default_timezone_set('America/Chicago');

// FROM THE POST AT EE
//$start = date("1899-12-30 h:i:s");
//$end = date($StartTime);

// A LITTLE BETTER EXAMPLE
echo $start = $StartTime;
$end   = "1899-12-30 h:i:s";

// AVOID THE STACK TRACE - REMOVE THE USELESS CHARACTERS
$start = preg_replace('/[^0-9 ]/', '', $start);

// SEE WHAT WE GOT
echo "<pre>";
$s = new DateTime($start);
var_dump($s);
$e = new DateTime($end);
var_dump($e);

// GET UNSIGNED TIMESTAMP NUMBERS SO WE CAN DO MATH
$sts = $s->format('U');
$ets = $e->format('U');
$dif = $ets - $sts;
var_dump($dif);

// TIMESTAMP IS SECONDS - GET THE DIFFERENCE IN MINUTES
$min = $dif / 60;
$min = (int)$min;
echo PHP_EOL . "$min MINUTES";
?>

Open in new window

0
 
LVL 10

Expert Comment

by:TRW-Consulting
Comment Utility
Take a look at your line: $end   = "1899-12-30 h:i:s";

That's why I was asking earlier if 'h:i:s' was literal, and it shouldn't be. You need to replace 'h' with a hour, 'i' with a minute, and 's' with a second.  So try changing that to:

$end   = "1899-12-30 00:00:00";

or some other reasonable figure.

Although I'm sure dates that far back work, but if you're only dealing with the hour/minute/seconds then perhaps you can work with it.

0
 
LVL 10

Expert Comment

by:TRW-Consulting
Comment Utility
That was supposed to read "although I'm *not* sure dates that far back work".
0
 
LVL 1

Author Comment

by:cbielich
Comment Utility
Ok I made the change so that it was not literal, I simply added

$nowtime = date("1899-12-30 h:i:s");
$start   = $nowtime;

and that gives it the literal numbers. Here is my output

object(DateTime)#1 (0) {
}
object(DateTime)#2 (0) {
}
float(35985)

599 MINUTES??

599 Minutes is wrong here are the two dates I used right when I ran this

1899-12-30 11:12:03
1899-12-30 01:12:18
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Did you understand what I was doing with the preg-replace() instruction?  That was to remove the h:i:s -- which was obviously useless to the computations.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Also, you might want to check the man page about date()
http://us.php.net/manual/en/function.date.php

The function expects two parameters, a format string and a unix timestamp.  If you omit the timestamp, you get the timestamp of "now".  So a statement like this...

$nowtime = date("1899-12-30 h:i:s");

... might not make much sense.  Best to print it out and see if it really is what you want.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility

<?php // RAY_temp_1899.php

error_reporting(E_ALL);



// MAN PAGE http://us.php.net/manual/en/datetime.gettimestamp.php



// REQUIRED FOR PHP 5.1+

date_default_timezone_set('America/Chicago');



// A NEW EXAMPLE

$end   = '1899-12-30 11:12:03';

$start = '1899-12-30 01:12:18';



// SEE WHAT WE GOT

echo "<pre>";

$s = new DateTime($start);

var_dump($s);

$e = new DateTime($end);

var_dump($e);



// GET UNSIGNED TIMESTAMP NUMBERS SO WE CAN DO MATH

$sts = $s->format('U');

$ets = $e->format('U');

$dif = $ets - $sts;

var_dump($dif);



// TIMESTAMP IS SECONDS - GET THE DIFFERENCE IN HOURS:MINUTES:SECONDS

$h_text = date('h', strtotime("TODAY + $dif SECONDS"));

$m_text = date('i', strtotime("TODAY + $dif SECONDS"));

$s_text = date('s', strtotime("TODAY + $dif SECONDS"));



echo "FROM $start TO $end THERE WERE $h_text HOURS, $m_text MINUTES, AND $s_text SECONDS";

Open in new window

0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 1

Author Comment

by:cbielich
Comment Utility
The now time is what I want on that one, here is the print out of the 2 dates

1899-12-30 11:12:03
1899-12-30 01:12:18

from what I can tell they look fine to me
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Please install and run the script I posted at ID:34105368.  Let us know if there is anything there that you do not understand.  Thanks, ~Ray
0
 
LVL 1

Author Comment

by:cbielich
Comment Utility
Here is the output, I ran your script exactly as it was

object(DateTime)#1 (0) {
}
object(DateTime)#2 (0) {
}
float(35985)
FROM 1899-12-30 01:12:18 TO 1899-12-30 11:12:03 THERE WERE 09 HOURS, 59 MINUTES, AND 45 SECONDS
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Perfect!  So now what is the question?
0
 
LVL 1

Author Comment

by:cbielich
Comment Utility
I guess I dont understand whats the difference between using a literal string as apposed to a variable that contains the exact same format. For instance I replaced

$end   = '1899-12-30 11:12:03';
$start = '1899-12-30 01:12:18';

with:

$end   = date("1899-12-30 h:i:s");
$start = $StartTime;

which outputs:

1899-12-30 02:27:48
1899-12-30 11:12:03

and I get a result of:

object(DateTime)#1 (0) {
}
object(DateTime)#2 (0) {
}
float(-31419)
FROM 1899-12-30 11:12:03 TO 1899-12-30 02:28:24 THERE WERE 06 HOURS, 00 MINUTES, AND 00 SECONDS

The 6 hourse 00 minutes and 00 seconds does not change even as I refresh
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Please post the EXACT script you are using now so I can install it and run it to see what it is doing.  Thank you, ~Ray
0
 
LVL 1

Author Comment

by:cbielich
Comment Utility
Here it is
<? include ('includes/connect.php'); ?>
<?
$today = date('Y-m-d') . " 00:00:00";
$sql = "SELECT * FROM `daycare attendance table` WHERE Date = '$today' AND StudentID = 'KB009' AND EndTime IS NULL";
$result = mysql_db_query($db,$sql,$cid);
$records = mysql_num_rows($result);
while($row = mysql_fetch_array($result)) {
extract($row);	
}

// RAY_temp_1899.php
error_reporting(E_ALL);

// MAN PAGE http://us.php.net/manual/en/datetime.gettimestamp.php

// REQUIRED FOR PHP 5.1+
date_default_timezone_set('America/Chicago');

// A NEW EXAMPLE
$nowtime = date("1899-12-30 h:i:s");
$end   = $nowtime;
$start = $StartTime;

// SEE WHAT WE GOT
echo "<pre>";
$s = new DateTime($start);
var_dump($s);
$e = new DateTime($end);
var_dump($e);

// GET UNSIGNED TIMESTAMP NUMBERS SO WE CAN DO MATH
$sts = $s->format('U');
$ets = $e->format('U');
$dif = $ets - $sts;
var_dump($dif);

// TIMESTAMP IS SECONDS - GET THE DIFFERENCE IN HOURS:MINUTES:SECONDS
$h_text = date('h', strtotime("TODAY + $dif SECONDS"));
$m_text = date('i', strtotime("TODAY + $dif SECONDS"));
$s_text = date('s', strtotime("TODAY + $dif SECONDS"));

echo "FROM $start TO $end THERE WERE $h_text HOURS, $m_text MINUTES, AND $s_text SECONDS";
?>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Also, looking at this:

float(-31419)

It appears that you may have a start time that occurs after the end time -- thus giving you a negative timestamp.  
0
 
LVL 1

Author Comment

by:cbielich
Comment Utility
Ok thats funny, didnt notice that now its seems to be working but my now time is off by 2 hours which could be the server let me check it and get right back to you
0
 
LVL 1

Author Comment

by:cbielich
Comment Utility
lol it was "date_default_timezone_set('America/Chicago');" in your code that was throwing off my time.

Another question why does the seconds count down instead of up?
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
date_default_timezone_set() is required now, as of PHP 5.1+

This is a dangerous line of code:

extract($row);      

Why?  Because it injects variables into your namespace.  You might want to reconsider that.

You can use var_dump($row) to print out the values in the $row array.  Then you will be able to see what is getting injected (var names and values).
0
 
LVL 1

Author Comment

by:cbielich
Comment Utility
For the sake of this example I am using it, I run a while loop in the real enviroment
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
I'm going to sign off on this question now.  Please go back and carefully read the article I posted a link to, above.  Attention to detail is important here.  For example, these are not equivalent, even though they may give you equivalent results during some times of day:

$nowtime = date("1899-12-30 h:i:s");
$nowtime = date("1899-12-30 H:i:s");

As one of my students said, "Even a stopped clock is right twice a day!"

best of luck with your project, ~Ray
0
 
LVL 1

Author Comment

by:cbielich
Comment Utility
Love that "As one of my students said, "Even a stopped clock is right twice a day!""
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Thanks for the points - have fun with it, ~Ray
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

763 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

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now