Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent PHP date() from defaulting to 12/31/1969

Tags:

date

php

default

I am using a MySQL database with PHP. I store my date values in the database using the DATETIME field.

I'm using this PHP code to convert inputted dates to the appropriate format for MySQL.

date("Y-m-d H:i:s", strtotime($inputDate))

However, whenever a date is invalid, it is placed in the database as 1969-12-31 19:00:00

Is there a way to default this to 0000-00-00 00:00:00 ?

like image 908
JoeBob Avatar asked Feb 08 '10 19:02

JoeBob


People also ask

How do I change the default date format in PHP?

Change YYYY-MM-DD to MM-DD-YYYY In the below example, we have date 2019-02-26 in YYYY-MM-DD format, and we will convert this to 02-26-2019 (MM-DD-YYYY) format. $orgDate = "2019-02-26"; $newDate = date("m-d-Y", strtotime($orgDate)); echo "New date format is: ".

How can I get current date in YYYY MM DD format in PHP?

$date = date("yyyy-mm-dd", strtotime(now));

How can set static date in PHP?

use a variable $datetime = date('Y-m-d H:i:s') .. it will store current date and time in $variable , and use $variable in all 50 insert queries.. so all time it will be same..

How can I get 30 Day date in PHP?

php $next_due_date = date('05/06/2016', strtotime("+30 days")); echo $next_due_date; ?> But it is returning to "05/06/2016" only!


1 Answers

Just detect validity with the output of strtotime(), which returns false on failure.

Something like:

$time = strtotime($inputDate);
$date = ($time === false) ? '0000-00-00 00:00:00' : date('Y-m-d H:i:s', $time);
like image 162
Mark Elliot Avatar answered Oct 13 '22 15:10

Mark Elliot