9

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.

Firze
  • 3,939
  • 6
  • 48
  • 61

5 Answers5

28

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.

Mike Brant
  • 70,514
  • 10
  • 99
  • 103
4
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))
Luke Wenke
  • 1,149
  • 2
  • 23
  • 43
3

Probably this:

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

if($first == $second) {
   // they are in same month
}
else {
   // they aren't
}
aksu
  • 5,221
  • 5
  • 24
  • 39
0

Try this

You can get month of unix timestamp simply using php date function.

So $date1 = 1393624800;

& $date2 = 1391472000 ;

You can easily check if month are same or not using date('m')

PHP CODE

if(date('m', $date1) == date('m', $date2)){ //Action; }

Hope this helps you :)

Krunal Panchal
  • 778
  • 7
  • 14
-1

Try this

$time = strtotime(date('Y-m-01 00:00:00')); // == 1338534000

Which translates to:

$date = date('Y-m-d H:i:s', $time); // == 2012-06-01 00:00:00

Read the PHP manual on the date() and time() functions.

Sumeet Gohel
  • 39
  • 1
  • 7