0

Of a given datetime I need the very end of the previous month.

For example:

$date_given = '2019-07-14 16:33:05';

should become:

2019-06-30 23:23:59

I have some possible solutions to make it in several lines. But the requirement for my program/script is to have it in one line. So something like this:

$date_result = ...somefunction..(($date_given) -1 month) ...;

It really would be helpfull to have everything in that one line and not have prior lines with functions.

Thanks.

DanielM
  • 317
  • 2
  • 11
  • 2
    Why does it need to be one line? That's not a logical requirement/constraint. – Dave Aug 15 '19 at 14:48
  • - one month is equal to `2019-06-14` – devpro Aug 15 '19 at 14:48
  • 1
    Set day of month to 1 then subtract 1 day. Then set time to 23:59:59. I dont understand why one liner Is required... But you can actualy type sentences to the datetime constructor So maybe you can do new datetime('last day of previous month') or so.... – slepic Aug 15 '19 at 14:51

2 Answers2

2

Here is many solution to this, but if has to be one line i would go with this

echo date_create($date_given.' last day of last month')->format('Y-m-d 23:59:59');
empiric
  • 7,825
  • 7
  • 37
  • 48
Hekimen
  • 174
  • 1
  • 2
  • 12
1

I actually don't know if there is a a way to dynamically get the last hour/minute/second of a day but I guess we can safely assume it always is "23:59:59" so you could do:

$lastDateOfMonth = date("Y-m-t 23:23:59", strtotime($date_given . '- 1 month'));
empiric
  • 7,825
  • 7
  • 37
  • 48