Home > Back-end >  PHP: Use of DateTime Relative Formats for times < or > current time
PHP: Use of DateTime Relative Formats for times < or > current time

Time:06-11

Does anybody know of an elegant way of using the PHP DateTime relative formats feature well for DateTime's that are not the current time?

Basically - I can create a new DateTime with a RelativeFormat from the current time very easily with

new DateTime('first monday of this week');

It would be incredibly useful to be able to do the same with other dates, so something like either:

new DateTime('first monday of 4 Jun 2022');  -> Should return  30 May 2022

or

$time = DateTime::createFromFormat('Y-m-d H:i:s', '2022-06-4 12:00:00);
$time->modify('first monday of week') -> Should return 30 May 2022

I know that this could be done with a function that mangles the date with various permutations of strtotime() but if anybody knows of a PHP library or something built into Relative Formats that I haven't found in the documentation which could achieve it more gracefully I'd be very grateful for the pointer.

CodePudding user response:

Your code works you are just missing "... this ..." in the first parameter of ->modify() as you want it to be relative to the DateTime describing that week.

<?php
$time = DateTime::createFromFormat('Y-m-d H:i:s', '2022-06-4 12:00:00');
$time->modify('first monday of this week'); //-> Should return 30 May 2022
var_dump($time);

/*
object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2022-05-30 00:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}
*/

echo $time->format('d M Y'); // 30 May 2022

Demo on 3v4l.org: https://3v4l.org/nNR7X


Alternatively for the exact values you provide you could have meant ->modify("last monday"); that also returns 30th of May for June 4th this year but it would give you the previous week if the input date is a Monday itself, e.g. June 6th this year.

CodePudding user response:

strtotime function is exactly what you are searching for. It gets reference time as second argument.

viz. https://www.php.net/manual/en/function.strtotime.php

CodePudding user response:

You can use strtotime and date functions:

$time = DateTime::createFromFormat('Y-m-d H:i:s', '2022-06-04 12:00:10');
var_dump(date('M j Y', strtotime('first monday of this week', $time->getTimestamp())));

output:

string(11) "May 30 2022"

  • Related