working with checkdate

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dila125
Forum Newbie
Posts: 7
Joined: Fri Apr 09, 2004 7:11 am

working with checkdate

Post by dila125 »

On an HTML form that my users fill in, I have a section for for them to enter a date. This is done through three listboxes, one for day (from 01 to 31), one for the month (01 to 12) and another for the year (2005 to 2010).

Of course the user could select an invalid date, such as 30th february 2006, so I wanted to use checkdate to check that the date is valid before the date is stored in the mysql database.

My theory was to convert the date to a timestamp, and use a while loop to increment the date by 86400 seconds until a valid date was found.

However, I was playing around with some code and found that when converting an invalid date (like 30th feb 2006) to a time stamp, it actually comes out as 2nd march 2006, so my above theory for the code is not going to work.

Code: Select all

if(!checkdate($_POST['productStockDateM'], $_POST['productStockDateD'], $_POST['productStockDateY']))
{
	$productStockDate = strtotime($_POST['productStockDateM'].'/'.$_POST['productStockDateD'].'/'.$_POST['productStockDateY']); 
	$productStockDate = $productStockDate + 86400;
	echo strftime ( "%d-%m-%Y", $productStockDate );
}
Can someone suggest a method for checking a date is valid, and if not valid, setting the date as the next valid date?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

<?php

$year = '2005';
$month = '2';
$day = '30';

$maxDate = date('Ymt', mktime( 0, 0, 0, $month, 1, $year ));

var_export($maxDate);

if($maxDate < sprintf('%04d%02d%02d',$year,$month,$day))
{
  echo 'date not valid'."\n";
}
else
{
  echo 'date valid'."\n";
}

?>
outputs:

Code: Select all

'20050228'date not valid
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Post by neophyte »

Feyd Rules. Almost everytime you post I learn something new! 8)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

now, just remember that you will need to validate everything, as the year and month could be out of range as well.. you'll need to check both upper and lower limits for the values sent on all (makes sure a circumvention of the dropdown's doesn't fail the computation for whatever reason)

luckily, month and year are far easier to range.. :)
Post Reply