Dane Iracleous
Dane Iracleous

Reputation: 1759

Getting a time interval based on a date string in PHP

Using strtotime(), I can get a specific timestamp, but what if I want to get an upper and lower bound based on the granularity of the string?

For example, if I specified "July, 2018" or "July" or "7/2018", I would want a lower bound timestamp of 2018-07-01 00:00:00, and an upper bound timestamp of 2018-07-31 23:59:59.

If I specified "July 3, 2018" or "2018-07-03" or "7/3/2018", I would want a lower bound timestamp of 2018-07-03 00:00:00, and an upper bound timestamp of 2018-07-03 23:59:59.

If I specified "2018", I would want a lower bound timestamp of 2018-01-01 00:00:00, and an upper bound timestamp of 2018-12-31 23:59:59.

Upvotes: 0

Views: 178

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35337

PHP datetime can parse first day and last day of months, documentation: http://php.net/manual/en/datetime.formats.relative.php

strtotime('first day of July, 2018');
strtotime('last day of July, 2018');

I don't know if you're going to find an existing solution to match exactly what you're looking for, but you should be able to write your own logic to accomplish this using the flexibility of relative strings datetime understands.

For year, it's always going to be XXXX-01-01 00:00:00 to XXXX-12-31 23:59:59 and for a specific date, it's always going to be XXXX-XX-XX 00:00:00 to XXXX-XX-XX 23:59:59, so those ones are pretty simple.

Upvotes: 2

Related Questions