PHP Date_add equivalent in 5.1.6

I'm trying to adjust a script for a client that needs to add 5 days to a date value.  Apparently date_add is a function that could be used in 5.3, but the ... guy (I'm being polite) to maintains the linux systems (if you could call it maintaining them) has 5.1.6 installed and there's almost no hope of that changing.  

So I need to find an equivalent function (or need someone to write an equivalent function) for 5.1 so I can do this.  I have VERY BASIC php knowledge - enough to decode and to a few simple things... this kind of function creation is out of my realm of knowledge.

Your help is greatly appreciated.
LVL 98
Lee W, MVPTechnology and Business Process AdvisorAsked:
Who is Participating?
 
Dave BaldwinFixer of ProblemsCommented:
This is something I use all the time.  It's from the PHP 'date' page.  Adjust for your needs.
$lastmonth = date("Y-m-d",mktime(0, 0, 0, date("m")-2, date("d"),   date("Y")));

Open in new window

http://php.net/manual/en/function.date.php
0
 
arnoldCommented:
Lee,

You could make the adjustment while pulling data from the ...

See http://php.net/manual/en/datetime.modify.php as the comments might help you.
0
 
Jim RiddlesPrepress/OMS SpecialistCommented:
This should be fairly straightforward.  To generate a date in PHP, you simply call the date() function.  See the following W3Schools site for it's use:
https://www.w3schools.com/php/func_date_date.asp

The following code will create a date that is five days after right now.  Adjust the format to your needs.
$date = date('Y-m-d',time() + (60 * 60 * 24 * 5));

Open in new window

If you are trying to add five days to an existing date, you will need to convert your current date to a unix timestamp.  Use the mktime() function to do that.
See the following W3Schools site for information on it's use: https://www.w3schools.com/php/func_date_mktime.asp
0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

 
Julian HansenCommented:
Use strtotime()

Add 5 days to a specified date
<?php
$date = '2017-11-09';
echo date('Y-m-d', strtotime($date . ' +5 days'));

Open in new window

Output
2017-11-14

Open in new window

0
 
Lee W, MVPTechnology and Business Process AdvisorAuthor Commented:
First, I may not have been clear initially - the date value I need to increase is not necessarily TODAY.  It could be a few days in the future (typically it IS a few days in the future), so using anything that references today as the date is not going to work for me.

For everyone's reference, I'm testing this out in a small script first - here's my code:

<?php

echo "Current PHP version: " . phpversion() ."\n";

$VARDATE = new DateTime("2017-11-27");
echo $VARDATE;

$VARDATE->modify('+5 days');
echo $VARDATE;
?>

Open in new window


arnold:
Thanks, but I'm getting an error "PHP Fatal error:  Class 'DateTime' not found in /home/lwilbur/test.php"

Dave:
I like this... I THINK I may be able to use this... BUT, I don't know how to adjust the starting date and if I'm reading your code correctly, that COULD result in invalid days like November 31.  I would need to use the month, day, and year and add the same number of days to each to ensure a valid date, especially with things like a new year.

Jim:
I thought of this (or rather, someone else suggested), but the problem of using a starting date other than today?
0
 
Jim RiddlesPrepress/OMS SpecialistCommented:
If the format of the date you are working with is as your example, then Julian's solution should do the trick.

Alternatively, you could still use my solution in combination with Julian's solution:
$old_date = '2017-02-11';
echo $old_date . '<br>';

$date = date('Y-m-d',strtotime($old_date) + (60 * 60 * 24 * 5));
echo $date;

Open in new window

0
 
arnoldCommented:
Lee, the reference modify applies to >=5.2 comments from users include the examples posted here using ....


Where is this data coming from.. If this data is being pulled from a db, you could change ...
0
 
Julian HansenCommented:
Please see my sample again

<?php
// THE DATE YOU ARE CONVERTING
$date = '2021-05-29';
// ADD 5 DAYS
echo date('Y-m-d', strtotime($date . ' +5 days'));

Open in new window


Output
2021-06-03

Open in new window


$date is representative of the date you want to add to - it can be any valid date. The strtotime() function is the easiest way of doing what you want as you can just specify how much you want to add (or subtract) from the string version of the date and it returns a valid date adjusted by the right number of days / months / years.
0
 
Dave BaldwinFixer of ProblemsCommented:
I like Julian's last post best.  'mktime' and 'strtotime' are written so they do not generate incorrect dates.
0
 
Jim RiddlesPrepress/OMS SpecialistCommented:
My original solution was to use mktime(), but strtotime() is a better function to use, given the date structure in the author's follow-up post.  Whether it is better to wrap the entire new date in strtotime(), or not, is debatable.  Julian's solution does that, while my solution only uses the strtotime() function to convert the original date, while still adding 5 days worth of seconds to increment the date.  Either way works.
0
 
Julian HansenCommented:
Either way works.
They do but the strtotime function specifically caters for date manipulation adding days, weeks, months years, hours minutes seconds - all using close to natural language without the need to do any calculations.
You can solve the problem with mktime and multiplying seconds out but the strtotime function was specifically written to cater for situations such as this.
0
 
Jim RiddlesPrepress/OMS SpecialistCommented:
I do not object to the way that this is being closed, but I will ask what the actual date value looks like that is entered by your user.  It looks like you are formatting it to look like "11-27-2017", if today's date was entered.  If that is the case, then the reason that strtotime() wasn't working with that format is it is trying to interpret it as day-month-year, since it is using "-" instead of "/".

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).

Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.

Note: Be aware of dates in the m/d/y or d-m-y formats; if the separator is a slash (/), then the American m/d/y is assumed. If the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. To avoid potential errors, you should YYYY-MM-DD dates or date_create_from_format() when possible.

If you had left it with the slashes, then I believe that it would have worked, but replacing the slashes with dashes caused strtotime() to incorrectly detect the date.
1
 
arnoldCommented:
Having a full picture of use could ....
I.e. If the data eventually goes into a db, during that time the date change could be made on SQL level using dateadd.
This presumes you do not need the date change in the php processing part.
0
 
Lee W, MVPTechnology and Business Process AdvisorAuthor Commented:
The data is used to directly edit text in a PDF file via a PERL script after it's pulled of a database.  It's asinine in so many ways, but what they have to work with until everything is redesigned.
0
 
Julian HansenCommented:
Why are you making it so complicated?
<?php
$date = '05/29/21';
echo date('Y-m-d', strtotime($date . ' +5 days')) . "<br>";
$date = '17-8-20';
echo date('Y-m-d', strtotime($date . ' +5 days')) . "<br>";
$date = "1/2/17";
echo date('Y-m-d', strtotime($date . ' +5 days')) . "<br>";
$date = "17-2-7";
echo date('Y-m-d', strtotime($date . ' +5 days')) . "<br>";
echo "Your dates <br>";
$date = "2017-11-27"; #Works
echo date('Y-m-d', strtotime($date . ' +5 days')) . "<br>";
$date = "12/1/17";
echo date('Y-m-d', strtotime($date . ' +5 days')) . "<br>";

Open in new window

Output
2021-06-03
2017-08-25
2017-01-07
2017-02-12
Your dates
2017-12-02
2017-12-06

Open in new window

strtotime() interprets many different date formats - no need to worry about leading zero's, forward slashes - as long as the dates obey the rules they will work in other words

y-m-d
OR
m/d/y

so
17-9-2 interpreted as 2017-09-02
1/2/17 interpreted as 2017-01-02

So your function becomes
function getdenialeffectivedate($date) {
	return date('Y-m-d', strtotime($date . ' +5 days'));
}

Open in new window

1
 
Lee W, MVPTechnology and Business Process AdvisorAuthor Commented:
Why are you making it so complicated?
As I said: I have VERY BASIC php knowledge.
There may be simpler ways of doing it, I may be concerned with things that are of no concern - which I don't know - I don't know what I don't know.

In my limited experience with mySQL and PHP, I've found weird things - for example, as I've stated, strtotime just DID NOT WORK.  The string, entered by the user in a text box, though it did not appear to have any special characters (and if it did, I could remove them with str_replace) but I drove myself crazy for hours trying to get strtotime to work until I tried the mktime function and changed things as I outlined which did work.  Should strtotime work?  probably... but it didn't.  And for all I know it's because the guy who "maintains" this system did something funky to cause problems... would not surprise me in the least - even if it meant one outdated library... whatever the case, it didn't work.
0
 
Julian HansenCommented:
I must have missed the post where you mentioned it did not work. Can you show us the implementation that did not work. I am interested to know why.
0
 
Lee W, MVPTechnology and Business Process AdvisorAuthor Commented:
In my closing comment:

I created a test script and function that would have used strtotime, and while the test script worked flawlessly, when trying to get it to work in the production one, it just wouldn't see the date string as a date.
0
 
Julian HansenCommented:
If the mktime() is working then this should work as well. It sounds like the dates are being entered with the wrong mix of / and -
UTC dates use - and are yyyy-mm-dd
US dates use / and are mm/dd/yyyy
If you mix these it is going to break the date functions.
So, I am guessing that this was the probably what was causing strtotime() to fail. One option is to use a datepicker on the front end that ensures the data is in the right format.
Either way this should work
function getdenialeffectivedate($date) {
   $date=str_replace("/","-",$date);
   $date=str_replace(" ","",$date);
   return date('Y-m-d', strtotime($date . ' +5 days'));
}

Open in new window

0
 
Lee W, MVPTechnology and Business Process AdvisorAuthor Commented:
You'd think.  But I was replacing spaces and / with - and outputing the entered date exactly as I set the variable.  Nothing appeared to be amiss.  The testing in the production code just refused to consider the date a date in the production code while working flawlessly in the test script.  mktime worked.
0
 
arnoldCommented:
the permanence deals with avoid user input issues by providing a calendar from which the person will choose the date?
0
 
Lee W, MVPTechnology and Business Process AdvisorAuthor Commented:
I was testing and clearly entering the date in same exact format the test variable used with the same exact date.  Yet the output of strtotime was ALWAYS 1/1/1970 + 5 days in the production system and exactly what I wanted in the test system.
0
 
Julian HansenCommented:
Usual practice is to find out the why of such anomalous behaviour - there might be something else lurking in your code or system that you would want to know about.

My pushing the point is not to be pedantic but based on years of experience in development were unexplained issues that should not be issues make me both curious and nervous.

The question here is what is different between prod and dev environments.
1
 
Lee W, MVPTechnology and Business Process AdvisorAuthor Commented:
This was a weird and annoying one... especially for me, NOT a PHP guy.

I created a test script and function that would have used strtotime, and while the test script worked flawlessly, when trying to get it to work in the production one, it just wouldn't see the date string as a date.  FYI, this was my test script:
[code]
<?php
function fixdate($date) {
        #Replace / with -
        $date=str_replace("/","-",$date);
        $parts=explode("-",$date);
        if ($parts[2] < 100) {
                $parts[2] = $parts[2] + 2000;
        }
        if ($parts[1] < 10) {
                $parts[1] = "0".$parts[1];
        }
        if ($parts[0] < 10) {
                $parts[0] = "0".$parts[0];
        }
        $date=$parts[2]."-".$parts[0]."-".$parts[1];
        return $date;
}

echo "Current PHP version: " . phpversion() ."\n";

$VARDATE = "2017-11-27"; #Works
$VARDATE = "12/1/17";
echo "Initial value: ".$VARDATE."\n";
$VARDATE = fixdate($VARDATE);
echo "  Fixed value: ".$VARDATE."\n";
$VARDATE = date("Y-m-d", strtotime($VARDATE) + 432000);
echo "  Later value: ".$VARDATE."\n";
?>[/code]

In the end, I used mktime to create a "certified" (as I'll call it) date/time value that then worked flawlessly just adding the number of seconds to the date value.  Here's the end function:
[code]
function getdenialeffectivedate($date) {
    #Replace / with -
    $date=str_replace("/","-",$date);
    $date=str_replace(" ","",$date);
    $parts=explode("-",$date);
    if ($parts[2] < 100) {
        $parts[2] = $parts[2] + 2000;
    }
    if ($parts[1] < 10) {
        $parts[1] = "0".$parts[1];
    }
    if ($parts[0] < 10) {
        $parts[0] = "0".$parts[0];
    }
    $date=mktime(0,0,0,$parts[0],$parts[1],$parts[2]);
    $date=date("m-d-Y", $date + 432000);
    return $date;
}

[/code]
There may be some unnecessary extra code in that especially relating to the leading zeros, but this worked.

Lastly, The date was entered in a web form by the end user.  It was not retrieved from a database.
0
 
Julian HansenCommented:
The input data is of more relevance than the script
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.