Xerrex
Xerrex

Reputation: 341

How can i compare two time variables in Php

I have two time variables time1 and time2 both of string type and with the format (yyyy:mm:dd HH:mm:ss). I need to compare them to get if:

  1. time1 = time2
  2. time1 < time2 or time2 < time1
  3. time1 > time2 or time2 > time1
  4. And when using the combination of the '=' and either '<'or '>'

Any help will be really appreciated. Am learning android together with php while doing a project for my Semester

Upvotes: 1

Views: 61

Answers (2)

Christian Pavilonis
Christian Pavilonis

Reputation: 92

strtotime() function can be helpful

Check out the documentation here for strtotime()

$str1 = "2016:4:9";
$str2 = "2016:1:1";
$time1 = strtotime($str1);
$time2 = strtotime($str2);

if ($time1 > $time2) { ...

Upvotes: 1

webGautam
webGautam

Reputation: 565

$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2);
var_dump($date1 < $date2);
var_dump($date1 > $date2);


// Output
bool(false)
bool(true)
bool(false)

More...

$dateA = '2008-03-01 13:34'; 
$dateB = '2007-04-14 15:23'; 
if(strtotime($dateA) > strtotime($dateB)){ 
    // ...
}

Upvotes: 0

Related Questions