PHP从时间戳获取上个月的名称

时间:2017-03-21 09:08:21

标签: php date unix-timestamp

我有一个Unix时间戳,想得到前一个月的名字e。 G。 " Ferbruary"

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

2 个答案:

答案 0 :(得分:2)

strtotime是你的朋友:

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

对于任何想要完全动态的人来说,要始终显示上个月的名字,代码将是:

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

答案 1 :(得分:-1)

您可以将DateTime对象设置为指定的时间戳,然后减去'P1M'(一个月)的间隔,如下所示:

/**
 * @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);
相关问题