-1

I Used <?php $febenddate=date('Y-2-t'); ?>

But Result is 2021-02-31, How can i get 2021-02-28 ?

  • 1
    `t` gives you the day of the *current* month (or of the timestamp of the second argument to `date`). It doesn't choose February just because you put a `2` into the format string… – deceze Mar 01 '21 at 08:42
  • What do you want to accomplish by getting date like that? – Hello World Mar 01 '21 at 08:43
  • It'd need some testing but you can probably do something as simple as `strtotime("last day of february $year")`. – Álvaro González Mar 01 '21 at 09:08

6 Answers6

2

You can use DateTime with a relative date expression.

$dateTime = date_create('Last Day of February 2021');

To output the date in the desired format:

echo $dateTime->format('Y-m-d');  //2021-02-28

If the year is omitted, February of the current year is used.

 $dateTime = date_create('Last Day of February');
jspit
  • 7,276
  • 1
  • 9
  • 17
1

You can use the function cal_days_in_month()

You need to provide the month and year for which you need to find the total no of days (or the end date)

cal_days_in_month (int $calendar, int $month, int $year) : int

In your case:

echo cal_days_in_month(CAL_GREGORIAN, 2, 2021); 

PHP Manual: cal_days_in_month

undefined
  • 1,019
  • 12
  • 24
nshah143
  • 549
  • 4
  • 22
0

To get the last day of February of the current year, first make a timestamp for any day in February—for which the 1st of February is a good choice—and get its t value. Just writing 2 in your date format string doesn't make it choose the t value of February:

echo date('Y-m-t', mktime(0, 0, 0, 2, 1));

See http://php.net/mktime.

deceze
  • 510,633
  • 85
  • 743
  • 889
-1

Try this one:

echo date("Y-m-t", strtotime("2021-02-14"));

The "t" in "Y-m-t" returns number of days in given month (param set in strtotime function). In short: you are echoing out: Y: Year, m: Month, t: Number of days in the given month in given year.

phingoc
  • 101
  • 1
  • 9
-1
$date=date_create("2021-02-28"); 

echo date_format($date,"Y-m-d");
Hkachhia
  • 4,463
  • 6
  • 41
  • 76
e404
  • 1
  • While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. – John Conde Mar 02 '21 at 01:00
-2

You can get the last date of Month using the below PHP Code ....

<?php
$d = new DateTime( '2021-02-01' );
echo $d->format( 'Y-m-t' );
?>
John Doe
  • 1,401
  • 1
  • 3
  • 14