diff, date_diff, abs - Calculating dates in PHP

2

Good afternoon everyone, there are Javascript Plugins as in PHP for calculating dates, I as I did not know how to calculate durations in PHP opted to do this work in the same javascript and post the already calculated result. I recently researched the subject as I am a beginner and I understand little English did not get anything fast that would explain how to calculate the duration between two dates and insert the result into the database. Obviously I came here, I did the questioning and did not get much success, I even knew that in PHP there was .diff() and .date_diff() but did not know .abs() .

Example:

$date1 = strtotime($_POST['data_inicio']);
$date2 = strtotime($_POST['data_fim']);
$duracao = date('H:i:s', abs( $date2 - $date1 ));

* As I did not know about abs() I was trying to do this with diff() .

Forgetting the Plugins and thinking about pure PHP I still would like something more comprehensive on this subject, and in Portuguese:

What are the methods of each? When should I use them? Are there other functions for calculating dates or duration in PHP?.

PS: If this subject is very simple, please excuse me, you can post a link of something already ready, or if the question is unnecessary it can be deleted.

Thank you in advance.

    
asked by anonymous 07.10.2016 / 22:43

2 answers

2

Definition

diff : This is the term used to make the comparison.

date_diff : This function is a nickname for : DateTime::diff() . Returns the difference between two DateTime objects.

<?php
   $datetime1 = new DateTime('2009-10-11');
   $datetime2 = new DateTime('2009-10-13');
   $interval = $datetime1->diff($datetime2);
   echo $interval->format('%R%a days');
?>

abs : Returns the absolute value. With respect to dates, you can create a series of dates beginning with the first day of the week for each week if you wish to populate a list on your web page with this mathematical date. Use the abs() function to convert negative numbers generated from dates in the past.

<?php
   $TwoWeeksAgo = new DateTime(date("Ymd"));
   $TwoWeeksAgo->sub(new DateInterval('P'.abs ( (7-date("N")-14)).'D'));
   $LastWeek = new DateTime(date("Ymd"));
   $LastWeek->sub(new DateInterval('P'.abs ( (7-date("N")-7)).'D'));
   $ThisWeek = new DateTime(date("Ymd"));
   $ThisWeek->add(new DateInterval('P'.abs ( (7-date("N"))).'D'));

   echo 'Start of This week is '.$ThisWeek->format('l m/d/Y').'<br/>';
   echo 'Start of Last week is '.$LastWeek->format('l m/d/Y').'<br/>';
   echo 'Start of 2 weeks ago is '.$TwosWeekAgo->format('l m/d/Y').'<br/>';
?>


Working with dates

I'd advise you to check out this part of the documentation.

Formatted current date : Function with no parameter that returns the date in the desired format.

function data(){
    return date('d/m/Y', time());
}

Format date : The most practical way to convert a date from one format to another.

$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));

Take the week number : If you need to know the number of a week, pass the date as a parameter of this function.

function weeknumber($ddate){
    $date = new DateTime($ddate);
    return $date->format("W");
}

Convert minutes to hours : Enter the minutes that the function will return the value in hours, and minutes if necessary.

function convertToHoursMins($time, $format = '%02d:%02d') {
    if ($time < 1) {
        return;
    }
    $hours = floor($time / 60);
    $minutes = ($time % 60);
    return sprintf($format, $hours, $minutes);
}

Difference between two dates : This function returns the time difference between two dates in hours and minutes.

function dateDiff($date1, $date2){
        $datetime1 = new DateTime($date1);
    $datetime2 = new DateTime($date2);
    $interval = $datetime1->diff($datetime2);
    return $interval->format('%H:%I');
}

Date in the past or future? List of conditions to know if a date is past, present or future.

if(strtotime(dateString) > time()) {
     # futuro
}

if(strtotime(dateString) < time()) {
     # passado
}

if(strtotime(dateString) == time()) {
     # presente
}

Calculate age : By reporting a date as a parameter, you can tell the age.

function age($date){
    $time = strtotime($date);
    if($time === false){
      return '';
    }

    $year_diff = '';
    $date = date('Y-m-d', $time);
    list($year,$month,$day) = explode('-',$date);
    $year_diff = date('Y') - $year;
    $month_diff = date('m') - $month;
    $day_diff = date('d') - $day;
    if ($day_diff < 0 || $month_diff < 0) $year_diff-;

    return $year_diff;
}

Days between two dates : A list of days between two dates you specify.

// Estabeleça o fuso horário
date_default_timezone_set('America/Sao_Paulo');

$start_date = new DateTime('2010-10-01');
$end_date = new DateTime('2010-10-05');

$period = new DatePeriod(
    $start_date, // 1st PARAM: start date
    new DateInterval('P1D'), // 2nd PARAM: interval (1 day interval in this case)
    $end_date, // 3rd PARAM: end date
    DatePeriod::EXCLUDE_START_DATE // 4th PARAM (optional): self-explanatory
);

foreach($period as $date) {
    echo $date->format('Y-m-d').'<br/>'; // Display the dates in yyyy-mm-dd format
}

Countdown to a date : Quick code to know how long, in days and hours, by a certain date.

$dt_end = new DateTime('December 3, 2016 2:00 PM');
$remain = $dt_end->diff(new DateTime());
echo $remain->d . ' days and ' . $remain->h . ' hours';
    
07.10.2016 / 23:10
2

Some details:

  • abs() is not to calculate date, it is to make an absolute value, for example a result of an account that generates negative value is converted to positive

  • DateTime is not a plugin, it's a native class

The problem there was solved with abs() because eventually some end dates in your form might come with an empty value or a value smaller than the start date, so that your calculation was ugly in a manual way.

So , the difference between using date + strtotime + abs and DateTime::diff is simply easy, basically you choose what you prefer, that DateTime class was created to make working with dates easier, avoiding having to write calculations or conversions "manually"

In short, DateTime does a lot of things, all focused on working time, which makes it much easier, now when using only date() or gmdate() you will have to adjust a lot and do it manually.

    
07.10.2016 / 23:19