2

I receive date values from web form in format dd/mm/YY (jquery datepicker) exmp: 13/07/2014

$date_from = $_POST['date_from'];
$date_to = $_POST['date_to'];

$newdate1 = date("Y-m-d 00:00:00", strtotime($date_from));
$newdate2 = date("Y-m-d 23:59:59", strtotime($date_to));

i need print all records from db where date is between this two dates:

SELECT * FROM db WHERE date BETWEEN '$newdate1' AND '$newdate2'"

It work fine until today because when i try select todays date 13/04/1014 (in jquery) and convert to format Y-m-d 00:00:00 script thinks 13 is month and return date 1970-01-01

0

2 Answers 2

1

The function strtotime expects to be given a string containing an English date format.

A basic solution is convert your format in english format

echo date('d-m-Y', strtotime(str_replace('/', '-', '13/07/2014');

output

13-07-2014

in your code

$date_from = $_POST['date_from'];
$date_to = $_POST['date_to'];

$newdate1 = date("Y-m-d 00:00:00",strtotime(date('d-m-Y', strtotime(str_replace('/', '-', $date_from)))));
$newdate2 = date("Y-m-d 00:00:00",strtotime(date('d-m-Y', strtotime(str_replace('/', '-', $date_to)))));
1

As the format required in the SQL query is different then the input format then it will create issues on multiple dates. Its better to convert your date to the appropriate format first and then run the query.

<?php
//Creating a function to convert date to required format
function formattedDate($dateStr, $inputFormat, $outputFormat) {
    $date = DateTime::createFromFormat($inputFormat, $dateStr);
    echo $date->format($outputFormat);
}

//Get input
$date_from = $_POST['date_from'];
$date_to = $_POST['date_to'];

//Get formatted date values
$newdate1 = formattedDate($date_from, "d/m/Y", "Y-m-d H:i:s");
$newdate2 = formattedDate($date_to, "d/m/Y", "Y-m-d H:i:s");
?>
1
  • @user3747585: and what is that ? Jul 14, 2014 at 8:29

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.