Nasıl geçerli ayı ve PHP kullanarak bir önceki üç aylık alabilirsiniz

6 Cevap php

Herhangi bir PHP kullanarak geçerli ayı ve önceki üç aylık almak için beni nasıl anlatacağım

Örneğin:

echo date("y:M:d");

çıkışı olacak: 09: Ekim: 20

Ama gerekir:

Ağustos

Eylül

Ekim

Çıktı olarak.

Şimdiden teşekkürler ...

Fero

6 Cevap

Ayın tam metinsel gösterimi için size "F" geçmek gerekir:

echo date("y:F:d");

bir önceki ay için kullanabileceğiniz

echo date("y:F:d",strtotime("-1 Months"));

Seyretmek dışarı için FUAH! Ayın 31 üzerinde yapıldığında, diğer cevaplar başarısız olur. Bunun yerine bu kullanın:

/*
Handles month/year increment calculations in a safe way,
avoiding the pitfall of 'fuzzy' month units.

Returns a DateTime object with incremented month values, and a date value == 1.
*/
function incrementDate($startDate, $monthIncrement = 0) {

    $startingTimeStamp = $startDate->getTimestamp();
    // Get the month value of the given date:
    $monthString = date('Y-m', $startingTimeStamp);
    // Create a date string corresponding to the 1st of the give month,
    // making it safe for monthly calculations:
    $safeDateString = "first day of $monthString";
    // Increment date by given month increments:
    $incrementedDateString = "$safeDateString $monthIncrement month";
    $newTimeStamp = strtotime($incrementedDateString);
    $newDate = DateTime::createFromFormat('U', $newTimeStamp);
    return $newDate;
}

$currentDate = new DateTime();
$oneMonthAgo = incrementDate($currentDate, -1);
$twoMonthsAgo = incrementDate($currentDate, -2);
$threeMonthsAgo = incrementDate($currentDate, -3);

echo "THIS: ".$currentDate->format('F Y') . "<br>";
echo "1 AGO: ".$oneMonthAgo->format('F Y') . "<br>";
echo "2 AGO: ".$twoMonthsAgo->format('F Y') . "<br>";
echo "3 AGO: ".$threeMonthsAgo->format('F Y') . "<br>";

Daha fazla bilgi için, benim cevap bakın here

Bu ay

date("y:M:d", mktime(0, 0, 0, date('m'), date('d'), date('Y')));

Önceki ay

date("y:M:d", mktime(0, 0, 0, date('m') - 1, date('d'), date('Y')));
date("y:M:d", mktime(0, 0, 0, date('m') - 2, date('d'), date('Y')));

Bu konuda OOP olmak istiyorsanız, bu deneyin:

$dp=new DatePeriod(date_create(),DateInterval::createFromDateString('last month'),2);
foreach($dp as $dt) echo $dt->format("y:M:d"),"\n"; //or "y F d"

çıkışlar:

  • 09: Ekim: 20
  • 09: Eylül: 20
  • 09: Ağustos: 20

Sen tarihini ("F") kullanmanız gerekir; tarih tam metin gösterimi olsun.