Reputation: 1979
I have the following datetime:
09/05/2016 09:12 (9 May 2016)
I want to get the day from it so I do
date('d', strtotime($date))
but this returns 05, which is the month.
What am I doing wrong ?
Upvotes: 3
Views: 1938
Reputation: 2010
This is because {J{ thinks it is an American date format.
Try changing the slashes (/)
to dashes (-)
// that is recognized as day month year, not month/day/year
09-05-2016
if you can't get the date in a different format you can do a str_replace to remove the slashes
$date = str_replace('/', '-', $date);
here is a link that may help you.
Upvotes: 4
Reputation: 9583
As you know that your date is not in correct format then re-format it like you want. Just create your date as you want.
date_create
will make a new date from your string.date_format
will convert your date as a new format Finally a
date
function with
strtotime
will display your desired result.
$str = "09/05/2016 09:12";
$date = date_create($str);
$time = date_format($date, "m-d-Y h:i");
echo date("d", strtotime($time)); //09
Upvotes: 0
Reputation: 4584
set format first your datetime by date()
. Then call your day!
$date = date("d/m/Y h:i",strtotime($date));//format your date as `09/05/2016 09:12`
var_dump(date("d",strtotime($date)));
Upvotes: 0
Reputation: 9123
Using the DateTime
class will give you alot more flexibility. For example: Take a look at the createFromFormat
method which can convert any format of date and time to a valid DateTime Object.
// Define your date
$date = '09/05/2016 09:12';
// convert it to a DateTime object
$date = DateTime::createFromFormat('d/m/Y H:i', $date);
// Output - returns 09
echo $date->format('d');
For more information take a look at PHP's Documentation on DateTime.
Upvotes: 3