Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to find out if 2 dates are in same month in PHP?

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?

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

like image 668
Firze Avatar asked Feb 04 '14 06:02

Firze


3 Answers

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
}

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.

like image 158
Mike Brant Avatar answered Nov 04 '22 20:11

Mike Brant


if (date("F Y", $date1) == date("F Y", $date2))

see http://au2.php.net/manual/en/function.date.php

that makes sure they are in the same month and year, otherwise do something like:

if (date("n", $date1) == date("n", $date2))
like image 4
Luke Wenke Avatar answered Nov 04 '22 21:11

Luke Wenke


Probably this:

$first = date("m", $timestamp);
$second = date("m", $timestamp2);

if($first == $second) {
   // they are in same month
}
else {
   // they aren't
}
like image 3
aksu Avatar answered Nov 04 '22 19:11

aksu