Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set 00:00:00 for DateTime

Tags:

php

What I want to get are

  • today's 00:00:00
  • week start day's 00:00:00
  • month start day's 00:00:00
  • year start day's 00:00:00

So I write the code,

$today = new \DateTime();
$weekStart = new \DateTime();
$monthStart = new \DateTime();
$yearStart = new \DateTime();

$weekStart->modify('last sunday');
$monthStart->modify('first day of this months');
$yearStart->modify('first day of this year');

print $today->format('Y-m-d h:i:s')."\n";
print $weekStart->format('Y-m-d h:i:s')."\n";
print $monthStart->format('Y-m-d h:i:s')."\n";
print $yearStart->format('Y-m-d h:i:s')."\n";

It gave me the result:

2018-11-13 09:34:02
2018-11-11 12:00:00
2018-11-01 09:34:02
2018-11-01 09:34:02

I have two questions.

How can I make each DateTime 00:00:00??

How can I get the first day of year???

like image 424
whitebear Avatar asked Mar 18 '26 18:03

whitebear


1 Answers

PHP's date parsing is somewhat tricky. Here's the code snippet which does what you want:

$today = new \DateTime('midnight');
$weekStart = new \DateTime('midnight last sunday');
$monthStart = new \DateTime('midnight first day of this month');
$yearStart = new \DateTime('midnight first day of january this year');


echo $today->format('Y-m-d H:i:s')."\n";
echo $weekStart->format('Y-m-d H:i:s')."\n";
echo $monthStart->format('Y-m-d H:i:s')."\n";
echo $yearStart->format('Y-m-d H:i:s')."\n";
  • DateTime value can be set upon construction; there's no need to call DateTime::modify().

  • Add midnight to get the time set to 00:00:00.

  • first day this year doesn't work in PHP, you need to use first day of january this year instead.

Reference: PHP Documentation of relative date formats.

like image 127
Alex Shesterov Avatar answered Mar 21 '26 07:03

Alex Shesterov