I have a Unix timestamp and would like to get the name of the preceding month e. g. "Ferbruary"
$date = 1489842000;
$lastMonth = getLastMonth($date); //Ferbruary
strtotime is your friend here:
echo Date('F', strtotime($date . " last month"));
For anyone that wants this fully dynamic, to always display last month's name, the code would be:
$currentMonth = date('F');
echo Date('F', strtotime($currentMonth . " last month"));
You can set a DateTime
object to the specified timestamp, then subtract an interval of 'P1M'
(one month), like this:
/**
* @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);