3

I have a text box where date is entered in php. Since I want the date to be in particular format I am using. date("d.m.Y", strtotime()) to conver the date. When no date is give or if I leave the textbox blank it will enter 1970-01-01 to database. How can I solve this? Here is my code

 $d_date= clean($_POST['datum']);
$newdate = date("Y-m-d", strtotime( $d_date));

If $d_date value is null the it will enter 1970-01-01 to database.

4
  • 1
    1970-01-01 00:00:00 is the starting time of Unix timestamps: en.wikipedia.org/wiki/Unix_time So if you enter 0 as timestamp, it is in fact 1970-01-01 00:00:00
    – Reeno
    Commented Jan 23, 2014 at 12:54
  • That is mostly because strtotime() is unable to create a time from the given string. What is contained in the $d_date variable?
    – shadyyx
    Commented Jan 23, 2014 at 12:54
  • Dupes stackoverflow.com/search?q=%5Bmysql%5D+1970-01-01
    – Mike B
    Commented Jan 23, 2014 at 13:00
  • $d_date value is blank. Commented Jan 23, 2014 at 13:12

3 Answers 3

9

Make field in the database nullable, and when date is not submitted in the form set it to NULL. Default behaviour of mysql is to set date to default value, which is 1970-01-01(unix epoch)

2
  • @MarcusAdams: Do you mean to say that strtotime( null ) or date( 'Y-m-d', null ) returns 1970....? Commented Jan 23, 2014 at 17:56
  • 1
    @Ravinder, date('Y-m-d', strtotime(null)) does. Commented Jan 23, 2014 at 18:43
1

PHP strtotime() returns false on failure. This includes if the parameter is null, blank. or any other invalidly formatted string.

So, strtotime(null) returns bool(false).

The second parameter for the date() function is an integer, so when you call date("Y-m-d", false), false gets converted to 0, and date("Y-m-d", 0), returns the epoch date.

Here's an easy way to handle this, prior to inserting the value into the database:

// Default to null
$newdate=null;
// Only proceed if strtotime() succeeds
if($d_date=strtotime($_POST['datum'])) {
  // Since we have a valid time, turn to date string
  $newdate=date("Y-m-d", $d_date);
}

Then, simply allow NULL on your date column so that null can be inserted.

1

you can use this to check strtotime return false or true

$from_date=strtotime($_POST["from"]); 
$from_date=($from_date ? date("Y-m-d", $from_date) : '');

$to_date=strtotime($_POST["to"]);
$to_date=($to_date ? date("Y-m-d", $to_date) : '');

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