I need to find if custom date provided by application user is less than today's date or not.

I'm trying following code:

$today    = JFactory::getDate();                        // 2015-06-14 16:54:50
$expected = JFactory::getDate($data['expected_date']);  // 2015-06-14 00:00:00

if ($expected < $today)
    throw new UnexpectedValueException(JText::_('COM_MYCOMPONENT_REQUEST_EXPECTED_DATE_ERROR'));

As you can see above, $today returns correct date but it returns with time which causes my if loop to fail.

I usually prefer Joomla way to implement any code. It's great!

1 Answer 1


I always compare dates with unix timestamps. In this day, there is no question about minutes or timezones.

if ($expected->toUnix() < $today->toUnix())

On the other hand, if you want to only compare only the date part, you can just format the dates and compare them with the simple string comparison:

if ($expected->format('Y-m-d') < $today->format('Y-m-d'))

In addition, when you receive a date, it may be on user timezone, so you could have to convert it:

$userTz = JFactory::getUser()->getParam('timezone');
$timeZone = JFactory::getConfig()->get('offset');

if ($userTz)
    $timeZone = $userTz;

$tz = new DateTimeZone($timeZone);
$date = JFactory::getDate($expected, $tz);
  • But here we are getting different time in both date. Hence we will get different UNIX timestamp for each date Jun 14, 2015 at 18:07
  • 1
    I see, you only want to compare the date parts. You could format both dates to $date->format('Y-m-d') and compare them as strings.
    – Anibal
    Jun 14, 2015 at 18:22
  • that's a great idea. I would request you to please update your answer along with what you have posted. :-) Jun 14, 2015 at 18:23
  • That's it. Answer updated!
    – Anibal
    Jun 15, 2015 at 14:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.