How to Get Number of Remaining Days Between Two Date in PHP

infoslearning

There is simple way to get the number of remainging days between two dates in PHP.  In Previous tutorial we learned how to get number of days between two dates. In this tutorial we will learn on how to get number of remaining 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 remaining days between two dates use the following script.

 <?php
 //include database connection here
  $sql="
    SELECT start_date,end_date, CURDATE() FROM date_range ";  
  $query =$dbh -> prepare($sql);
  $query->execute();
  $results=$query->fetchAll(PDO::FETCH_OBJ);

  $sn=1;
  if($query->rowCount() > 0)
  {
  foreach($results as $row)
  {  
  $endDate = strtotime($row->to_date);
  $startDate = strtotime($row->from_date);
  $todaysDate = strtotime(today);
  $days = ($endDate - $startDate) / 86400 + 1;
  $leftdays=($endDate - $todaysDate) / 86400;
  echo $leftdays;
  }
  }
  ?>

Strtotime() - Parse English textual datetimes into Unix timestamps:

CURDATE() –This function returns current date.


Other Recommended for you

  • .What is Cloud Firestore? Android Studio
  • .Firebase Realtime Database vs Firestore.
  • .What is an Intent in Android? Types of Intent
  • .What is Firebase?