Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a PHP function to test a zero date

Tags:

php

datetime

Looking for a shorthand or better way to test a zero date (MySQL datetime column) other than:

if ($row['this_date'] == '0000-00-00 00:00:00') echo 'No date set.';

Is there a PHP function that test it? Thanks.

like image 330
H. Ferrence Avatar asked Apr 08 '11 10:04

H. Ferrence


People also ask

How do you check if a date is empty?

Use the value property to check if an input type="date" is empty, e.g. if (! dateInput. value) {} . The value property stores the date formatted as YYYY-MM-DD or has an empty value if the user hasn't selected a date.

Is date function in PHP?

Definition and Usage. The date() function formats a local date and time, and returns the formatted date string.


6 Answers

I think you don't need any shorthand.
It's sort of some micro-optimization.

You have already spent more time asking this question than can save you such a shorthand in a year of average coding. Just write it and move on.
Don't you have more important problems to solve?

Moreover, with such a shorthand you will obfuscate your own code.
Your current statement is perfectly clear, reads "if date is empty"
but all proposed snippets aren't that clear. Coming to this code months later, you will puzzle yourself with question, if such a code monster have any special meaning.

What you actually wanted is readability. But you have it already. While all proposed shorthands don't.

like image 109
Your Common Sense Avatar answered Sep 24 '22 08:09

Your Common Sense


What about:

if(strtotime($row['this_date']) == 0) echo 'No date set.';
like image 30
Jonathan Gimeno Avatar answered Sep 25 '22 08:09

Jonathan Gimeno


Although you should probably use NULL in your database, a simple hack would be:

if(!(int)$row['this_date'])echo'No Date Set.';

What kind of better way are you expecting to find? it's fast as it is.

P.S. It's a hack because I'm assuming you will have a year set. Meaning it won't work for the string 0000-00-00 00:00:01

like image 24
Khez Avatar answered Sep 26 '22 08:09

Khez


Being a fan of regular expressions, I'll add another one:

if (!preg_match('/[1-9]/', $row['this_date'])) echo 'No date set.';
  • Works also with timestamps and other stuff.
  • Obviously does not check for date consistency.
like image 33
syck Avatar answered Sep 27 '22 08:09

syck


if (strtotime($row['this_date'])) echo 'No date set.';
like image 37
Manu Avatar answered Sep 26 '22 08:09

Manu


You can use the following code

$date = '0000-00-00 00:00:00';
if(str_replace(array("-", " ", ":"), "", $date)*1>0){
    echo "DATE";
} else {
    echo "NODATE";
}
like image 39
berkayunal Avatar answered Sep 24 '22 08:09

berkayunal