1

I know this was asked before, but I looked at all those solutions and they don't work for me. Theirs start with a format that I'm not starting with, but even so I tried their solutions anyway and I kept getting a 1970 year as my end date.

So I have a start date in the format of mm-dd-YYYY, and I want to add 35 days to it to create an end date. The following is what I finally was able to make work, but it's inconsistent, or maybe I was wrong and it doesn't really work.

I convert the start date to YYYY-mm-dd because that's what i noticed works better with the strtotime function. I tried converting it differently but nothing worked except doing it the explode way.

So after format conversion then adding the days and converting format back, for some reason it adds like 49 days, even though I am specifying 35 days.

I don't know what else to try.

$startdate = "08-13-2015";
$pieces = explode("-", $startdate);
$newdate = $pieces[2]."-".$pieces[0]."-".$pieces[1];
$enddate = date('m-d-Y', strtotime($newdate. ' + 35 days'));
echo $enddate; //result is 10-01-2015 when it should be 09-17-2015

UPDATE

modified for my need. using variable as the start date.

$inputdate = new DateTime($startdate);
$inputdate->modify('+35 days');
$enddate = $inputdate->format('m-d-Y');

Get the following errors when the page with the code is ran:

Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (08-13-2015) at position 0 (0): Unexpected character' in path\file.php on line 9002
Exception: DateTime::__construct(): Failed to parse time string (08-13-2015) at position 0 (0): Unexpected character in path\file.php on line 9002

9002 says this:

$inputdate = new DateTime($startdate);
leoarce
  • 567
  • 2
  • 8
  • 33

3 Answers3

2

DateTime with DateTime::modify() should do it, as shown.

$date = new DateTime('08-13-2015');
$date->modify('+35 days');
echo $date->format('m-d-Y');

But check your PHP version first, if it's below 5.1 you won't be able to use it and under 5.3 you'll face some minor bugs.

al'ein
  • 1,711
  • 1
  • 14
  • 21
  • see my updated question – leoarce Aug 12 '15 at 17:18
  • Did you see the edit made at your question? Follow the link and see if it answers your issue. Also, check this one: http://stackoverflow.com/questions/17427503/php-datetime-construct-failed-to-parse-time-string-xxxxxxxx-at-position-x – al'ein Aug 12 '15 at 17:24
1

you can do it with mktime

$startdate = "08-13-2015";
$pieces = explode("-", $startdate);
$newdate2 = mktime(12, 0, 0, $pieces[0], $pieces[1] + 35, $pieces[2]);
$enddate2 = date('m-d-Y', $newdate2);
var_dump($enddate2); // 09-17-2015
mmm
  • 1,070
  • 1
  • 7
  • 15
0

you need to read this http://php.net/manual/en/book.datetime.php or use a date library like carbon https://github.com/briannesbitt/Carbon

Jamal Rahani
  • 105
  • 4