I have problem to convert one of my dates in YYY-d-m format.
I have the array $searchQuery, which when print using print_r, prints the foloowing output:
Array ( [selectedArea] => 0
[checkin] => 30/07/2014
[checkout] => 01/08/2014
[rooms] => 1
[adults] => 2
[childrens] => 0 )
I have the following code:
echo "Checkin is:" .$searchQuery['checkin']."<br />";
$what = strtotime($searchQuery['checkin']);
echo "New checkin is:" .$newCheckin = date('Y-m-d', $what) ."<br />";
echo "Checkout is:" .$searchQuery['checkout']."<br />";
$newCheckOutTemp = strtotime($searchQuery['checkout']);
echo "New checkout is:" .$newCheckout = date('Y-m-d', $newCheckOutTemp) ."<br/>";
Which prints the following:
Checkin is:30/07/2014
New checkin is:1970-01-01 ------>????
Checkout is:01/08/2014
New checkout is:2014-01-08
I have two questions...why the first date is printing 1970-01-01 when converted, and second, how can i the difference in days between those 2 dates.
Any help will be deeply appreciated.
Regards, John
try with datetime()
$now = new DateTime(str_replace('/', '-','30/07/2014'));
echo $now->format('Y-m-d');
$newCheckOutTemp = new DateTime(str_replace('/', '-','01/08/2014'));
echo $newCheckOutTemp->format('Y-m-d');
or with date()
echo date('Y-m-d', strtotime(str_replace('/', '-',$what)));
echo $newCheckout = date('Y-m-d', strtotime(str_replace('/', '-',$newCheckOutTemp)));
For day difference here so many answers :- Date Difference in php on days?
I think you have to try: date('Y-m-d', strtotime($what))
instead of date('Y-m-d', $what)
It appears that strtotime() expects your date format to be m/d/Y. As you are passing the date starting with month 30, it doesn't know how to handle it and returns you the date 1970-01-01. If you look closely at the checkout result, it is probably not the same as you expect (8th of January instead of 1st of August).
What I would do is write a little helper function to handle all your dates.
function formatDate($date) {
return \DateTime::createFromFormat('m/d/Y', $date)->format('Y-m-d');
}
And then later use it like this:
$newCheckin = formatDate($searchQuery['checkin']);
$newCheckout = formatDate($searchQuery['checkout']);