diff, date_diff, abs - PHP date calculation

Asked

Viewed 2,638 times

3

Good afternoon everyone, there are plugins in both Javascript and PHP for calculating dates, I as I did not know how to calculate durations in PHP chose to do this work in the same javascript and post the result already calculated. Recently I researched the subject as a beginner and understand little English I could not get anything fast that would explain me how to calculate the duration between two dates and insert the result in the database. Obviously I came here, I carried out the questioning and I had little success, until I knew that in PHP .diff() and the .date_diff() but did not know of .abs().

Example:

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

*How did you not know abs() was trying to do this with diff().

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

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

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

Thank you from Now.

  • You want to know when to use each of them?

  • That, how each one works and if there are other options.

  • 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, the difference between using date+strtotime+abs and Datetime::diff is simply easy, basically you choose what you prefer, but you only have to understand that the Datetime class was created to facilitate working with dates, avoiding having to write calculations or conversions "manulamente".

2 answers

4


Definition

diff: Is the term used to make the comparison.

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

<?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 starting with the first day of the week for each week if you want to fill a list on your web page with this mathematical date. Use the function abs() to convert negative numbers generated from past dates.

<?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 advise you to see this part of documentation.

Current date formatted: Function without 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));

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

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

Convert minutes to hours: Inform 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 in the past, present or future.

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

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

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

Calculate age: By entering a date as a parameter, you can know 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 specified by you.

// 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, until a given 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';

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, is a native class

The problem there was solved with abs() because eventually some end dates in your form might have come with empty value or less than the start date, so that calculation of yours was ugly manually.

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.