PHP get last month name from timestamp

I have a Unix timestamp and would like to get the name of the previous month e. g. "Ferbruary"

$date = 1489842000;
$lastMonth = getLastMonth($date); //Ferbruary

      

+3


source to share


2 answers


strtotime is your friend here:

echo Date('F', strtotime($date . " last month"));

      



For those who want to be fully dynamic to always display the last month's name, the code would look like this:

$currentMonth = date('F');
echo Date('F', strtotime($currentMonth . " last month"));

      

+2


source


You can set the object DateTime

to a specified timestamp, then subtract the interval 'P1M'

(one month), for example:



/**
 * @param {int} $date unix timestamp
 * @return string name of month
 */
function getLastMonth($date) {
    // create new DateTime object and set its value
    $datetime = new DateTime();
    $datetime->setTimestamp($date);
    // subtract P1M - one month
    $datetime->sub(new DateInterval('P1M'));

    // return date formatted to month name
    return $datetime->format('F');
}

// Example of use
$date = 1489842000;
$lastMonth = getLastMonth($date);

      

-1


source







All Articles