Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I target a specific day of the current month with DateTime::modify?

Tags:

php

datetime

I need to be able to set a DateTime object to a certain day of the current month. I can obviously do this by getting the current month and creating a new DateTime, or checking the current day and creating a DateInterval object to modify the DateTime, but I want to just give plain text arguments to DateTime::modify.

I'm looking for something like:

$datetime->modify('10th day this month');

but this gives me an error like

PHP Warning: DateTime::modify(): Failed to parse time string (10th day this month) at position 0 (1): Unexpected character in php shell code on line 1

and I don't seem able to find the correct construction of the sentence to make PHP play nicely.

like image 920
shanethehat Avatar asked Nov 22 '13 15:11

shanethehat


People also ask

How do I find the first and last date of the month?

To get the first and last day of the current month, use the getFullYear() and getMonth() methods to get the current year and month and pass them to the Date() constructor to get an object representing the two dates.

How can get first and last day of month in php?

php $query_date = '2010-02-04'; // First day of the month. echo date('Y-m-01', strtotime($query_date)); // Last day of the month. echo date('Y-m-t', strtotime($query_date));


2 Answers

It isn't possible to get the Xth day of a given month directly, but you can achieve this with a simple workaround:

$datetime->modify('last day of previous month')->modify('+10 day');

Another alternative would be:

$datetime->format('Y-m-10');
like image 58
Amal Murali Avatar answered Nov 13 '22 13:11

Amal Murali


If you must use DateTime::modify() then this workaround may suit you:-

$date = new \DateTime();
$date->modify($date->format('Y-m-10'));

Although it probably isn't any better than Amal's answer, I offer it here just as an alternative that avoids the double call.

Demo

like image 30
vascowhite Avatar answered Nov 13 '22 15:11

vascowhite