[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 181
  • Last Modified:

How to compare two time strings properly?

Experts,

I would like to know the best way to compare two strings which contain a time.

Example:

$test = '10:01am';

if($test < '10:00am'){
echo 'am shift';
}else{
echo 'pm shift';
}

Open in new window


Should I convert the times to a different format before executing the comparison?

Cheers!
0
evibesmusic
Asked:
evibesmusic
  • 3
1 Solution
 
Marco GasiFreelancerCommented:
Since you're dealing with strings, you could just check if string 'am' is in your string $test:

$test = '10:01am';
if (stristr('am', $test))
{
  echo 'am shift';
}
else
{
  echo 'pm shift';
}

Open in new window


But since you're dealing with date strings, I'm sure Ray will suggest his wonderful article soon: be patient to get a higher knowledge level :-)
0
 
Ray PaseurCommented:
Yes, convert the time strings.  Follow the guidance in this article when dealing with date and time values.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html
0
 
Ray PaseurCommented:
Example here: http://iconoun.com/demo/temp_evibesmusic.php

<?php // demo/temp_evibesmusic.php
ini_set('display_errors', TRUE);
error_reporting(E_ALL);

/* SAMPLE FROM http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28502041.html

$test = '10:01am';

if($test < '10:00am'){
echo 'am shift';
}else{
echo 'pm shift';
}
*/

// TEST DATA
$test = '10:01am';
$time = '10:00am';

// CONVERT TO TIMESTAMPS
$ts_test = strtotime('TODAY ' . $test);
$ts_time = strtotime('TODAY ' . $time);

// COMPARE THE VALUES
if ($ts_test < $ts_time)
{
    echo $test . " IS AM SHIFT";
}
else
{
    echo $test . " IS PM SHIFT";
}

Open in new window

HTH, ~Ray
0
 
evibesmusicAuthor Commented:
Thank you as always Ray.
0
 
Ray PaseurCommented:
Glad to help.  Once you read the article you will see how easy this can be in PHP!
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now