rgomez
rgomez

Reputation: 185

PHP Date conversion to SQLSrv

I'm having some troubles with some SQLSrv dates and PHP. Here is the code:

echo date_format($startDate, 'd/m/Y');
echo date_format($endDate, 'd/m/Y');

$endDate = date('Y-m-d', strtotime(date_format($endDate, 'd/m/Y')));
$startDate = date('Y-m-d', strtotime(date_format($startDate, 'd/m/Y')));

The result from the above echo is: 10/10/201613/10/2016 which is ok because that's what I'm fetching from the Database. But as the code runs I'm using the 2 strings inside a while to insert into Sqlsrv DB again into Date format the $startDate is inserted as 2016-10-10 on all rows which is ok but the $endDate is inserted as 1970-01-01.

Can't figure out what is wrong.

Upvotes: 0

Views: 932

Answers (1)

rgomez
rgomez

Reputation: 185

Answering my own question the error was on the conversion so I found out I needed to replace / with - here is the code where both strings are returned ok. Thanks @WEI_DBA for pointing me out to that:

$endDate = date_format($endDate, 'd/m/Y');
$endDate = str_replace('/', '-', $endDate);
$endDate = date('Y-m-d', strtotime($endDate));

$startDate = date_format($startDate, 'd/m/Y');
$startDate = str_replace('/', '-', $startDate);
$startDate = date('Y-m-d', strtotime($startDate));

Upvotes: 1

Related Questions