Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

date - php: datetime() difference between 2 datetime with 2 variables

I have in my database 4 columns which are:

Date_in | Time_in | Date_out | Time_out

Date_in and Time_in belong together (e.g., 2013-02-18 13:00:00) and date_out goes with Time_out. I would like to find out the difference between and I have gotten up till:

$start_time = new DateTime("'$list[date_in] "."$list[time_in]'");
$since_start = $start_time->diff(new DateTime("'$list[date_out] "."$list[time_out]'"));

$hours = $since_start->h.' hours';

But it doesn't work. I think my quotes and double quotes are all messed up because the use of " ' . really confuses me..

Thanks in advance for any advice on how I can fix my code!

[EDIT] Thanks everyone for all your detailed help! I just realised that the server doesn't support php 5.3 and I can't use datetime().

So my solution was:

$start_time = strtotime("$list[date_in] " . "$list[time_in]");
$end_time = strtotime("$list[date_out] " . "$list[time_out]");
$hours = abs(($end_time - $start_time)/3600);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this,

function datediff( $date1, $date2 )
{
    $diff = abs( strtotime( $date1 ) - strtotime( $date2 ) );

    return sprintf
    (
        "%d Days, %d Hours, %d Mins, %d Seconds",
        intval( $diff / 86400 ),
        intval( ( $diff % 86400 ) / 3600),
        intval( ( $diff / 60 ) % 60 ),
        intval( $diff % 60 )
    );
}

print datediff( "18th February 2013", "now" ) . "
";

OR

You can use DateTime::diff

  $start_date = new DateTime("2012-02-10 11:26:00");
    $end_date = new DateTime("2012-04-25 01:50:00");
    $interval = $start_date->diff($end_date);
    echo "Result " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";

EDIT:

Checkout links,

How to calculate the difference between two dates using PHP?

Php Date Time – 7 Methods to Calculate the Difference between 2 dates.

may help you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...