Page 1 of 1

Adding to Dates

Posted: Sat Jun 16, 2012 9:56 am
by PhilAJ
This has to be so simple but i just cant get the syntax right, can anybody help please.

I have an input date field from a form, extracted into $startdate and also a numeric field of hours $hours and want to create an $enddate that is startdate plus that number of hours.

I have tried every combination of strtotime; mktime; etc but just cant get it.

Help would be much appreciated...

Re: Adding to Dates

Posted: Sat Jun 16, 2012 10:31 am
by Celauran

Re: Adding to Dates

Posted: Sat Jun 16, 2012 11:25 am
by PhilAJ
Thanks Celauran...yes Ive loooked at this but just cant get the syntax right...

tried...

$date = date_create($startdate);
date_modify($date, '+$period.h'); //$period has an integer of 'hours' to be added
echo date_format($date, 'Y-m-d H:i:s');

...but just get errors

can you advise of correct syntax?

Re: Adding to Dates

Posted: Sat Jun 16, 2012 12:27 pm
by califdon
I've usually found strtotime() to be the simplest and most flexible way to adjust a datetime value. You will get much more helpful answers if you show us the exact error messages you receive. Date and time manipulation can be tricky, and my guess is that your problem is that you are not supplying the functions with the data types they expect. That is fundamentally important for all functions, and especially for date/time functions. If the manual specifies that an argument is a string, you must supply it with a string; if it specifies a datetime, you must supply it with a datetime (which is actually just a long number, namely the number of seconds since the beginning of the Unix epoch). Take a look at what data type your variable $startdate that you probably received as a $_POST variable from your form. It is a string. If it is formatted as an English date/time (see http://php.net/manual/en/function.strtotime.php and http://www.php.net/manual/en/datetime.f ... mpound.php), then you can convert it to datetime with strtotime() and then apply the hours increment with another call to strtotime(). If your $startdate content conforms to this format, your code might look like this:

Code: Select all

$newdate = strtotime("+$hours hours",strtotime($startdate));
If it doesn't conform, you may have to use date_create() or such to format it correctly for the strtotime().

I haven't tried the above, but it's similar to what I've written many times.

Re: Adding to Dates

Posted: Sat Jun 16, 2012 2:04 pm
by PhilAJ
Thanks califdon - sussed it out.

I has a strtotime on an existing 'date' format field - took this out, put a few echo's in, and its fine

Thanks for eveeryones help

Phil