➩ subtract 2 dates in PHP and show the days results tutorial and free code

Technology

header ads

➩ subtract 2 dates in PHP and show the days results tutorial and free code

show the days results between 2 dates in PHP code tutorial and free code | difference between 2 dates

subtract 2 dates in PHP and show the days results tutorial and free code
subtract 2 dates in PHP and show the days results tutorial and free code


when the programmers in a php project we must use a function in php where you can show the days subtracted between 2 dates in this case we will take an old date: 11/05/2018 where this post was written and the date of today , we will use format which will give us the solution to know the days.

First we will change the old date as DateTime, to be able to use the function and subtract the days, but we will first use the function of php time (), in the following way:





date_default_timezone_set('America/new_york');
$time = time();
$dia1 = date("d", $time);
$mes1 = date("m", $time);
$ano1 = date("Y", $time);
$hhorao = date("h", $time);
$fechadehoy = $ano1 . '-' . $mes1 . '-' . $dia1;


where $fechadehoy in php date takes today's exact date in both days, months and year, date_default_timezone_set takes the local time on the server at the time it is captured.


then we use a function called restardias which will return the days subtracted between these 2 dates:





function restardias($datetime1, $datetime2) {
   // echo '' . $datetime1 . ' ' . $datetime2;
    $interval = $datetime1->diff($datetime2);
    $restar = $interval->format('%R%a');
    return $restar;
}



In the old date we save it in a variable $fecha_ temp = "05/11/2018"; finally I will leave the complete code calling the function and showing the days subtracted with echo:




<?php
date_default_timezone_set('America/new_york');


function restardias($datetime1, $datetime2) {
   // echo '' . $datetime1 . ' ' . $datetime2;
    $interval = $datetime1->diff($datetime2);
    $restar = $interval->format('%R%a');
    return $restar;
}
$time = time();
$dia1 = date("d", $time);
$mes1 = date("m", $time);
$ano1 = date("Y", $time);
$hhorao = date("h", $time);
$fechadehoy = $ano1 . '-' . $mes1 . '-' . $dia1;
$fecha_temp="11/05/2018";
 $datetime2 = new DateTime($fechadehoy);
  $datetime1 = new DateTime($fecha_temp);
    $rest = restardias($datetime1, $datetime2);
    echo 'days results of the 2 dates:'.$rest;

?>

if you liked this post please share on social networks or with a friend programmer who is interested in the buttons on the web, I hope I have helped you until our next code

Post a Comment