How to Get Number of Days Between Two Date in PHP
There is simple way to get the number of days between two dates in PHP. In this tutorial we will learn on how to get number of days between two dates specified.
Create table in your database, for example date_range.sql
-- phpMyAdmin SQL Dump
-- version 5.1.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Mar 18, 2022 at 09:23 AM
-- Server version: 10.4.22-MariaDB
-- PHP Version: 8.1.2
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `ngome_db`
--
-- --------------------------------------------------------
--
-- Table structure for table `date_range`
--
CREATE TABLE `date_range` (
`id` int(11) NOT NULL,
`start_date` varchar(20) DEFAULT NULL,
`end_date` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `date_range`
--
INSERT INTO `date_range` (`id`, `start_date`, `end_date`) VALUES
(1, '2022-01-01', '2022-12-31');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `date_range`
--
ALTER TABLE `date_range`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `date_range`
--
ALTER TABLE `date_range`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Then, to count days between two dates use the following script.
<?php
//include database connection heare
include("connection.php");
//query
$sql="SELECT * FROM date_range";
$query =$dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
if($query->rowCount() > 0)
{
foreach($results as $row)
{
$endDate = strtotime($row->end_date);
$startDate = strtotime($row->start_date);
$days = ($endDate - $startDate) / 86400 + 1;
echo $days;
}
}
?>
Strtotime - Parse English textual datetimes into Unix timestamps:
Note: Be aware of dates in the m/d/y or d-m-y formats.