Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create DateTime string for the beginning and the end of the day

Tags:

php

If I have a string of the following:

"2013-10-28"

and when I convert to a DateTime using the following function:

new \DateTime("2013-10-28");

it always gives me a DateTime with the time not set.

I want to have two DateTime :

  • one marking the beginning of the day, meaning at 00:00:00
  • another DateTime which is on the same date but at the end of the day 23:59:59.

How do I do this given the string above?

like image 583
adit Avatar asked Oct 29 '13 09:10

adit


People also ask

How to convert a string to datetime?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

What is datetime strptime?

strptime() is another method available in DateTime which is used to format the time stamp which is in string format to date-time object.


2 Answers

Use DateTime::setTime

$d = new \DateTime("2013-10-28");
$d->setTime(23, 59, 59);
like image 115
Daniel Hepper Avatar answered Oct 19 '22 18:10

Daniel Hepper


Have a look at all possible compound formats.

The MySQL format should be the easiest for your use case:

new \DateTime("2013-10-28 00:00:00");
new \DateTime("2013-10-28 23:59:59");
like image 33
ComFreek Avatar answered Oct 19 '22 17:10

ComFreek