0

Having trouble getting a way to increment a string date by one day.

So it starts off with 30/01/2001 for example.

$linedata[8] = 30/01/2001;

Then I use date parse form format.

$thetime = date_parse_from_format("j/n/Y",$linedata[8]);

The return is in array. Is it possible to increment the date from this array or should i be parsing the date with a different function?

0

3 Answers 3

1

You don't want to use date_parse_from_format() as that just gives you a lot of date parts which requires you modifying the appropriate ones and then reassembling them. You also have issues with leap years and working with the last day of the month.

You want to use DateTime::createFromFormat() which gives you a DateTime object which is easy to work with and handles things like leap years and the number of days in a month:

$date = DateTime::createFromFormat("j/n/Y", '30/01/2001');
$date->modify('+1 day');
echo $date->format('Y-m-d');

Demo

Sign up to request clarification or add additional context in comments.

8 Comments

Looks neat but i'm returned an error, Fatal error: Call to a member function modify() on a non-object ..... is it a php version issue?
What version are you using? This will work with PHP 5.3+
version is 5.4.22. i just checked the modify function and should be fine as 5.2.0
This should work. What actual date are you using in your test? It's possible the format we are providing the function is wrong.
Is your $linedata[8] defined as 30/01/2001 or as '30/01/2001'? The first is 30 divided by 1 divided by 2001; the second is a human-formatted date string
|
0

You can increment the date like this:

$thetime["day"]++;

or

$thetime["day"] = $thetime["day"] + 1;

then you can get the incremented date like this

$idate = $thetime["day"]."/".$thetime["month"]."/".$thetime["year"];

1 Comment

What happens on February 28th in a non-leap year? Or January 31st?This totally breaks.
0

This would work (providing $linedata[8] contains a date):

$thetime = date('j/n/Y', strtotime($linedata[8] . ' +1 day'));

1 Comment

That date format is not one strtotime can work with.

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.