Comparison of dates - PHP

Asked

Viewed 106 times

2

I have the following comparison:

# Verifica se está em tempo habil para concluir a transacao
if($transacao->data_expira <= date("Y-m-d H:i:s")." 000000"){
    echo "Ainda é permitido pagar"; 
} else {
    echo "Esta cobrança não pode ser mais paga!";
}

Where $transcao->data_expira is = 2017-10-05 15:42:54.000000

Data Atual: 2017-10-04 19:14:20
Data Expira: 2017-10-05 15:42:54

In this case, payment would have to be allowed. How can I make this comparison correctly?

  • Related: https://answall.com/questions/33469/como-comparar-datas-em-php

  • $transacao->data_expira is the type DateTime?

2 answers

2


Taking into account that $transacao->data_expira is the type DateTime, you can compare using the function ->diff(), see:

if ($transacao->data_expira->diff(new DateTime("today")) >= 0) {
    echo "Ainda é permitido pagar";
} else {
    echo "Esta cobrança não pode ser mais paga!";
}

Case $transacao->data_expira not be the type DateTime, start a new instance to then compare them.

$data_expira = new DateTime($transcao->data_expira); // 2017-10-05 15:42:54
$hoje = new DateTime("today"); // 2017-10-04
$intervalo = $data_expira->diff($hoje);
echo $interval->format("%a days"); // 1 days

See it working on ideone

  • Possible, but failed. Call to a Member Function diff()

  • The format is date and time

  • 1

    I have explained how to start the DateTime @Andrébaill

1

You can compare the timestamp of the dates so:

if (strtotime($numerical." ".$day." of ".date("F")) < time()) {
    // Mais velho
} else {
    // Mais novo
}

Before converting the date to str breaking the same.

Timestamp

A time tag (or time stamp) is a string denoting the time or date a certain event occurred. The string is usually presented in a consistent format, allowing easy comparison between two distinct time marks.

They are standardized by the International Organization for Standardization (ISO) through ISO 8601.

Source: https://en.wikipedia.org/wiki/Timestamp

Browser other questions tagged

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