0

I am coverting a time differnce function I made over a year ago in javascript to a php function. Most of it is pretty similar but there's one part I just cant figure out. the setMonth() function is kind of similar to $date->modify, but the values are returned in different formats and it's confusing me. If any one can find a php equivelent to the following javascript I would be most grateful. Thanks.

 var date1 = new Date();
 var date2 = date('some date');

 var dayDiff = date1.setMonth(date1.getMonth() + month);   
 var  day = Math.abs(Math.floor((date2.getTime() - dayDiff) / (1000 * 60 * 60 * 24)));
3
  • instead of giving us the JS tell us what you want to do Commented Nov 16, 2014 at 22:12
  • Plus the fact that it's simply a bad code in JS. dayDiff isn't the day difference, it's the current date month + an amount of months added... As @Dagon said, you better know what you really want, don't try to port things that seem badly coded. Is it a function that returns the number of days difference between the {currentDate} and the {currentDate + n * months}? Commented Nov 16, 2014 at 22:21
  • this part ofthe function is to determine the amount of days after a month as there are different numbers of days in month eg. 32 days could be a month and one day in January or it could be a month and 4 days in February. the varable names are bit confusing. sorry Commented Nov 16, 2014 at 22:27

1 Answer 1

1

Official website of php: http://php.net/manual/fr/datetime.diff.php

Add your months using -> modify

$currentDate -> modify('+' . $months . ' month');

Get the date difference using -> diff

$interval = $currentDate -> diff($otherDate, true);

The second boolean parameter indicates that you do not care about negative differences, output will always be positive (as your Math.abs did in the javascript version).

And output it with -> format

$interval->format('%R%a days')


Full example

// If you need to set the timezone
date_default_timezone_set('America/New_York');

// Whatever month you want to add to $currentDate
$months = 2; // months has to be an int

$currentDate = new DateTime();
$otherDate   = new DateTime('2014-01-04');

$currentDate -> modify('+' . $months . ' month');

$interval = $currentDate -> diff($otherDate, true);

echo($interval->format('%R%a days'));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.