Just wanted to record some nuance with the answer by lorem monkey
The suggested method might cause issues with when using time zones.
scenario: consider current system time is 2018-01-01 00:20:00 UTC
and system default time zone is set to UTC.
date('Y')
will give you 2018
if you are doing something like:
$startDate = new DateTime('first day of january '.date('Y'), new DateTimeZone('America/New_York'));
This will compute to 'first day of january 2018'
but you actually needed the first date of your current year in America/New_York, which is still 2017.
Stop dropping the ball man, its not new year yet!
So it is better to just do
$startDate = new DateTime('first day of january', new DateTimeZone('America/New_York'));
And then do the modifications as needed by using the DateTime::modify()
function.
Relative date formats are fun.
My scenario: I wanted to get the bounds of this year as in 2018-01-01 00:00:00
to 2018-12-31 23:59:59
This can be achieved in two ways with relative date formats.
one way is to use the DateTime::modify()
function on the object.
$startDate = (new DateTime('now', new DateTimeZone("America/New_York")));
$endDate = (new DateTime('now', new DateTimeZone("America/New_York")));
$startDate->modify("january")
->modify("first day of this month")
->modify("midnight");
$endDate->modify("next year")
->modify("january")
->modify("first day of this month")
->modify("midnight")->modify("-1 second");
var_dump([$startDate, $endDate]);
Try out here: https://www.tehplayground.com/Qk3SkcrCDkNJoLK2
Another way to do this is to separate the relative strings with a comma like so:
$startDate = (new DateTime('first day of january', new DateTimeZone("America/New_York")));
$endDate = (new DateTime('next year, first day of january, -1 second', new DateTimeZone("America/New_York")));
var_dump([$startDate, $endDate]);
Try out here: https://www.tehplayground.com/hyCqXLRBlhJbCyks
$year = new DateTime('first day of january');
not ok?new \DateTime('first day of January this year')
ornew \DateTime('last day of December next year')
for example...'first day of this year'
returns a valid Date but not the first day of this year? Makes it sense?