I am trying to replace the current day with the last day of the month but the error returns
Call to member function setDate() on string
on the last line. Everything is working correctly except for the setDate function
//current date which is 2017-08-28 10:50:30
$string = $date1;
$dateM = DateTime::createFromFormat("Y-m-d H:i:s", $string);
//getting the day of the month which is 28
$dateMonth = $dateM->format("d");
//if the day is 28
if($dateMonth >= 28){
//change the day to 31
$dateMonth = 31;
//current date which is 28/08/2017
$out = $date1;
//replace 28 with 31
$date1 = $out->setDate($out->format('Y'), $out->format('m'), $dateMonth , $out->format('H'), $out->format('i'), $out->format('s'));
}
You can use t
in format specifier on DateTime
's format
function.
format character: t
Description: Number of days in the given month
Example returned values: 28 through 31
<?php
$input = '2017-08-28 10:50:30';
$date_time = DateTime::createFromFormat('Y-m-d H:i:s', $input);
$last_day_of_month = $date_time->format('Y-m-t H:i:s');
echo $last_day_of_month;
This gives:
2017-08-31 10:50:30
Demo: https://eval.in/844314
The error message says, that $out
is String
not DateTime
object. So you something mixed up.
Maybe should be $out = $dateM;
instead of $out = $date1;
?
Setting $dateMonth
to 31
might not be a good idea as come months have 30 days in. PHPs data function allows you to use t
as a format, which gives you the number of days in the given month. So you could use that to get the last day of the current month:
date("Y-m-t")