简体   繁体   中英

Comparing date strings in PHP

Given the following strings in PHP:

$startDate = "2015-12-17";
$startTime = "11:16 AM";
$startTimezone = "(GMT +00:00) Dublin, London";

$endDate = "2017-12-17";
$endTime = "11:16 AM";
$endTimezone = "(GMT -06:00) Central Time";

The formats will always be:

YYYY-MM-DD for the date

HH:MM AM|PM for the time

Whats the best way to determine if:

  • The start date and time is not in the past
  • The end date and time is not in the past
  • The end date and time is after the start date and time
  • (Note timezones can be different)

I'm guessing using the PHP DateTime class, and comparing them, but unsure exactly how to construct it for my use case?

I did not test it, but it should work something like this:

$startDate = "2015-12-17";
$startTime = "11:16 AM";
$startTimezone = "+0000";

$endDate = "2017-12-17";
$endTime = "11:16 AM";
$endTimezone = "-0600";

$start = DateTime::createFromFormat("Y-m-d h:i A O", $startDate . ' ' . $startTime . ' ' . $startTimezone);

$end = DateTime::createFromFormat("Y-m-d h:i A O", $endDate . ' ' . $endTime . ' ' . $endTimezone);

$now = new DateTime();

if ($start > $now && $end > $now && $start < $end) {
    // do stuff
}

As you can see I used a different format for the timezones. You can choose one yourself. See the timezone section of this page for that: http://php.net/manual/en/function.date.php

Try this,

<?php

$startDate = "2015-12-18";
$startTime = "3:53 PM";

$endDate = "2017-12-17";
$endTime = "11:16 AM";

$reset = date_default_timezone_get();

date_default_timezone_set('America/New_York');

$start = strtotime($startDate.$startTime);
$end = strtotime($endDate.$endTime);
$curTime   =   strtotime(now);

date_default_timezone_set($reset);



if($st_time < $curTime)
{
   // Start time is less than current time - not past
}

if($end < $curTime)
{
   // End time is less than current time - not past
}

if($end < $start)
{
   // End time is less than start time
}

?>

Some other methods are there, but I tried this in one of my project and it worked without any issues.

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM