Shirantha
Shirantha

Reputation: 71

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 ?

Upvotes: 0

Views: 115

Answers (2)

Jake
Jake

Reputation: 47

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">

Upvotes: 1

Lovepreet Singh
Lovepreet Singh

Reputation: 4850

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.

Upvotes: 0

Related Questions