在 PHP 中找出两个日期是否在同一个月的最佳方法是什么?

问题描述:

我有 2 个日期是 unix 时间戳,我必须弄清楚这些日期是否在同一个月.例如,如果我有 1393624800 = 02/28/141391472000 = 2/4/2014.我想我可以将 unix 时间戳转换为 28-02-2014 之类的格式并提取月份,但我觉得它有点肮脏的方法.这样做的最佳方法是什么?

I have 2 dates that are unix time stamps and I would have to figure out if the dates are in same month. For example if I have 1393624800 = 02 / 28 / 14 and 1391472000 = 2 / 4 / 2014. I figured I could convert the unix time stamps to format like 28-02-2014 and extract the month, but I feel like its kinda dirty method. What is the best way to do this?

对不起,我忘了.还必须确保是同一年.

Sry I forgot. Also have to make sure its the same year.

我建议使用 DateTime 类

I would suggest using the DateTime class

$date1 = new DateTime();
$date1->setTimestamp($timestamp1);

$date2 = new DateTime();
$date2->setTimestamp($timestamp2);

if ($date1->format('Y-m') === $date2->format('Y-m')) {
    // year and month match
}

我强烈建议任何学习 PHP 的人学习 DateTime 和相关课程.它们比基本的日期函数强大得多.

I would highly suggest to anyone learning PHP to learn the DateTime and related classes. They are much more powerful than the basic date functions.