1

I have date strings in "Y-m" format. Day is irrelevant here. Now I need to create another date from these date strings wheere day should be either 1st or the last day of the month. I have tried this code:

$curDate = DateTime::createFromFormat('Y-m', $datestring1);
$dt =  $curDate->format('Y-m-d');

The problem here is that it creates dates with the current day of the months. How can I force it to do it for the 1st or last day?

Thanks

user2723490
  • 2,010
  • 4
  • 27
  • 37

2 Answers2

6

first day:

$dt = $curDate->format('Y-m-01');

last day:

$dt = $curDate->format('Y-m-t');

t: Number of days in the given month

http://php.net/manual/en/function.date.php

C. Leung
  • 6,218
  • 3
  • 20
  • 32
1

You can specify hard code value

$curDate = DateTime::createFromFormat('Y-m', $datestring1);
$dt =  $curDate->format('Y-m-1'); //if you want first day
$dt =  $curDate->format('Y-m-t'); //if you want last day
Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90