日期/字符串比较

时间:2014-01-24 11:37:49

标签: php string date

我需要比较两个日期,其中一个日期实际上是一个字符串。 所以我从今天('d / m / y')得到今天的日期,从我的数据库中的某个地方得到另一个日期。 这个字符串看起来像'dd / mm / yyyy'。

我不知道如何比较它们,我一遍又一遍地试过但是我无法让它运转起来。 这是代码

<?
  require_once '/web/ticket/src/event/Event.php';
  require_once '/web/ticket/src/ticket/Ticket.php';

  $tickets = Ticket::getTickets();
  $events = Event::getEvents();

  $today = date('d/m/Y');

  foreach($events as $k => $event) {
    $data_1 = $event['data_singolo'];
    $data_2 = $event['data_a'];

    if($today>$data_1 || $today>$data_2) {
       Event::setInvalid($event['_id']);
    } else {
      echo "evento attivo<br><br>";
    }
  }

  foreach($tickets as $k => $ticket) {
    $event = Event::getEventById($ticket['event_id']);
    if($event['valid']==0) {
      Ticket::setInvalid($ticket['_id']);
    }
  }
?>

PS。 “数据”表示“日期”;

2 个答案:

答案 0 :(得分:1)

如果您需要特殊的非标准日期格式,可以使用DateTime类。 :)

<?
  require_once '/web/ticket/src/event/Event.php';
  require_once '/web/ticket/src/ticket/Ticket.php';

  $tickets = Ticket::getTickets();
  $events = Event::getEvents();

  $today = new DateTime("today");

  foreach($events as $k => $event) {
    $data_1 = DateTime::createFromFormat("d/m/Y", $event['data_singolo']);
    $data_2 = DateTime::createFromFormat("d/m/Y", $event['data_a']);

    if($today>$data_1 || $today>$data_2) {
       Event::setInvalid($event['_id']);
    } else {
      echo "evento attivo<br><br>";
    }
  }

  foreach($tickets as $k => $ticket) {
    $event = Event::getEventById($ticket['event_id']);
    if($event['valid']==0) {
      Ticket::setInvalid($ticket['_id']);
    }
  }
?>

答案 1 :(得分:0)

我的代码真的很乱,所以我最终得到了这个。

<?
require_once '/web/ticket/src/event/Event.php';
require_once '/web/ticket/src/ticket/Ticket.php';

$tickets = Ticket::getTickets();
$events = Event::getAllValidEvents();

$today = date("d/m/Y");

foreach($events as $k => $event) {
 if($event['tipo_data']=='1') {

  $data_singolo = $event['data_singolo'];
  $data_singolo_chunks = array_map('intval', explode('/', $data_singolo));
  $data_1 = date("d/m/Y", mktime(0, 0, 0, $data_singolo_chunks[1], $data_singolo_chunks[0], $data_singolo_chunks[2]));

  if($today>$data_1) {      
    Event::setInvalid($event['_id']);
  }
} else {

  $data_a = $event['data_a'];
  $data_a_chunks = array_map('intval', explode('/', $data_a));
  $data_2 = date("d/m/Y", mktime(0, 0, 0, $data_a_chunks[1], $data_a_chunks[0], $data_a_chunks[2]));    

  if($today>$data_2) {      
   Event::setInvalid($event['_id']);
  }
}
}

foreach($tickets as $k => $ticket) {
$event = Event::getEventById($ticket['event_id']);
if($event['valid']==0) {
  Ticket::setInvalid($ticket['_id']);
}
}
?>