简体   繁体   中英

counting number of days in a date range using php?

I want to use a function to output the number of days within a date range

to do that i use something like below;

$from = $_POST['from'];
$to  = $_POST['to'];

$numdays = date_diff($to,$from);

but, when i out put the $numdays it always "0". How can I get this right ?

any clues ?

You must convert the string to a date format to calculate then convert back to a string to display it

<?php
if(isset($_POST['from']) && isset($_POST['to'])){
    $from = date_create($_POST['from']);
    $to  = date_create($_POST['to']);
    $numdays = date_diff($from,$to);
    echo $numdays->format("%r%a days");

}

?>

<form action="" method="post">
<lable for="from">from</lable>
<input type="date" name="from" id="from">
<lable for="to">to</lable>
<input type="date" name="to" id="to">
<input type="submit">

First create date object for dates using date_create and then calculate difference as:

$numdays = date_diff(date_create($_POST['from']), date_create($_POST['to']))->format('%a');

Read more about date_diff .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM