2/01/2010

Easy PHP Date Picker

There are many fancy javascript calendars for selecting dates - for example the one that comes as a jQuery plugin is really cool. There are however some disadvantages to using such calendars:


  • If you only need a date picker, it's not worth to include all these Javascript libraries and overload.

  • These javascript calendars are hard to use from people who don't see well or can't use a mouse

  • In admin screens etc., where you may need to manage many dates in rows of records, clicking on the calendars can be much slower than picking dates from dropdown.



In cases like these and maybe more, it's better to create a simple dropdown date picker that will allow the user to select year, month and day (in fact this will be 3 dropdowns).

Let's build such a function:

First we'll build an array of months:

$months=array('','January','February','March','April','May','June','July','August',
'September','October','November','December');


Note that I inserted the first element of the array as empty because I want the month numbers to start from 1 (for January).

Then we'll construct the three dropdowns:

$html="<select name=\"".$name."month\">";
for($i=1;$i<=12;$i++)
{
$html.="<option value='$i'>$months[$i]</option>";
}
$html.="</select> ";


This was the months dropdown. Did you notice the "name" variable? We will pass it as argument to the function so we can control the name of the dropdowns and have many of them in a page. In very similar way you can create the days dropdown - from 1st to 31st.


$html.="<select name=\"".$name."day\">";
for($i=1;$i<=31;$i++)
{
$html.="<option value='$i'>$i</option>";
}
$html.="</select> ";


The years dropdown is just as simple. The only question in it is in what year to start and when to end. Your function can accept this as arguments or you can dynamically create start and end year accordingly to the current date. For example:


$startyear = date("Y")-100;
$endyear= date("Y")+50;

$html.="<select name=\"".$name."year\">";
for($i=$startyear;$i<=$endyear;$i++)
{
$chooser.="<option value='$i'>$i</option>";
}
$html.="</select> ";


You can add some javascript to increase/reduce the number of days accordingly to the month, but this can be needlessly complicated. It's easier to solve this problem by javascript validation at the time when the form is submitted.

So Here Is The Full Code (For Those Who Don't Get It):



Then put all this code into a function which accepts the argument $name:


function date_picker($name, $startyear=NULL, $endyear=NULL)
{
if($startyear==NULL) $startyear = date("Y")-100;
if($endyear==NULL) $endyear=date("Y")+50;

$months=array('','January','February','March','April','May',
'June','July','August', 'September','October','November','December');

// Month dropdown
$html="<select name=\"".$name."month\">";

for($i=1;$i<=12;$i++)
{
$html.="<option value='$i'>$months[$i]</option>";
}
$html.="</select> ";

// Day dropdown
$html.="<select name=\"".$name."day\">";
for($i=1;$i<=31;$i++)
{
$html.="<option $selected value='$i'>$i</option>";
}
$html.="</select> ";

// Year dropdown
$html.="<select name=\"".$name."year\">";

for($i=$startyear;$i<=$endyear;$i++)
{
$html.="<option value='$i'>$i</option>";
}
$html.="</select> ";

return $html;
}


And use the function as echo date_picker("registration") (for example - "registration" is just a name you choose). The result that will come in $_POST after submitting such form will be in 3 variables:
$_POST['registrationmonth'], $_POST['registrationday'] and $_POST['registrationyear'].

You can easily construct a MySQL date from these variables.

Now think how you can make this dropdown read stored data and pre-select its values accordingly to it (for "Edit record" forms).

47 comments:

  1. A date picker that allows you to pick 31st of Feb.

    What a fail.

    ReplyDelete
  2. nice but
    $startyear = date("Y")-100;
    $startyear = date("Y")+50;

    should look like
    $startyear = date("Y")-100;
    $endyear = date("Y")+50;

    :]

    ReplyDelete
  3. Thanks Aleksander ;)

    PaulG, this is a SIMPLE date picker. As the tutorial states it's for example used in admin panels. If you want to add validation, add it with javascript.

    ReplyDelete
  4. Solution for above problem is :
    After POST is called we can check the Date
    CODE :

    $selMonth = $_POST['registrationmonth'];
    $selDay = $_POST['registrationday'];
    $selYear = $_POST['registrationyear'];

    if (checkdate($selMonth, $selDay, $sleYear))
    {
    //Proceed
    }
    else
    {
    // Not Valid Date
    }

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. How do you set a specific date

    ReplyDelete
  7. Im gonna give it a go, trying (really hard) to include a date picker in my contact form. Its using php mailer to send collected data to my email but I havent been able to insert it into my form till now. Will let you know how this ends...

    ReplyDelete
  8. Nice one!! I love this post! I have now inserted the date picker in my website.. However, I am not sure on how to have my data sent to another form. Please help anyone??

    ReplyDelete
  9. I published an updated version on http://www.linaccess.com/content/easy-php-date-picker

    This version extends the function, giving you the ability to pass a timestamp to pre-select a date

    ReplyDelete
  10. BRilliant- allowed me to fill date arrays on a form with 20 date inputs.
    But I'm stumped as to how to make this dropdown read stored data and pre-select its values accordingly to it (for "Edit record" forms). Help!!!

    ReplyDelete
  11. No let's not. I want to get the son of a bitch date converted to a mother fucking SQL timestamp. I've looked at 25 sites that fail how to explain how to fucking do this .

    ReplyDelete
  12. how to use this function with html form

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. There is an error in Full Code

    in section for 'Day dropdown' remove $selected as it is undefined and generates an error.

    Thank you. It helped immensely.

    ReplyDelete
  15. Very good, very easy to implement without javascript

    ReplyDelete
  16. i have one problem that how can i call this in my php code

    ReplyDelete
  17. I have a smal update to the code to have it return todays selected date as default to the form. It is handy for web applications who usually want todays date.
    http://pastebin.com/efLWNest

    ReplyDelete
  18. How do you arrange the year in reverse order?

    ReplyDelete
    Replies
    1. Change
      for($i=$startyear;$i<=$endyear;$i++)
      to
      for($i=$endyear;$>i=$startyear;$i--)

      Delete
  19. i keep getting "Undefined index: begindatumday" i used: echo date_picker("begindatum"); and $bgday = $_POST['begindatumday'];

    ReplyDelete
  20. This comment has been removed by the author.

    ReplyDelete
  21. Implemented the function in a form. Works fine, specially when combined with a datecheck as mentioned by Anish on September 22, 2011.
    However when i submit the form, the date displayed in the dropdowns is accepted as input by $_POST. This means that existing data in the database may be overwritted with an accidental value in the dropdowns. How do I prevent my form to recognize non changed datefields and act accordingly?

    Thnx Hans Metselaar


    if (($_POST['testday']) OR ($_POST['testmonth']) OR ($_POST['testyear']))
    {
    $testday = ($_POST['testday']); $testmonth = ($_POST['testmonth']); $testyear= ($_POST['testyear']);
    $datumfout = 'N';
    if (checkdate($testmonth, $testday, $testyear))
    { // datum is OK
    $testdatum = $testyear . '-' . $testmonth . '-' . $testday;
    $sql = mysql_query("UPDATE var_app SET testdatum = '$testdatum' WHERE app_id='1' ") or die (mysql_error());
    }
    else
    { // datum fout, display error
    $datumfout = 'J';
    }
    }

    ReplyDelete
  22. First of all thank you for sharing this informative blog.. This concept explanation are very easy and step by step so interesting to read and also useful to develop the web development skills

    php training and job placement | best php training institute in chennai velachery

    ReplyDelete
  23. I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.
    Hadoop Training in Chennai
    Hadoop Training in Bangalore

    ReplyDelete
  24. Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.
    Hadoop Training in Bangalore

    ReplyDelete
  25. I and my friends were going through the nice, helpful tips from the blog then the sudden came up with an awful suspicion I never expressed respect to the website owner for those secrets.
    MEAN stack training in chennai

    ReplyDelete
  26. Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage contribution from other ones on this subject while our own child is truly discovering a great deal. Have fun with the remaining portion of the year.
    Hadoop Training in Bangalore

    ReplyDelete
  27. Really great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries. I want to say thanks for great sharing.
    Data Science Training in Chennai
    Data science training in bangalore
    Data science online training
    Data science training in pune
    Data science training in kalyan nagar

    ReplyDelete
  28. Woah this blog is wonderful i like studying your posts. Keep up the great work! You understand, lots of persons are hunting around for this info, you could help them greatly.
    Python training in marathahalli
    Python training institute in pune

    ReplyDelete
  29. I’d love to be a part of group where I can get advice from other experienced people that share the same interest. If you have any recommendations, please let me know. Thank you.
    nebosh course in chennai

    ReplyDelete

  30. It seems you are so busy in last month. The detail you shared about your work and it is really impressive that's why i am waiting for your post because i get the new ideas over here and you really write so well.

    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training
    Selenium training in bangalore

    ReplyDelete
  31. It’s great to come across a blog every once in a while that isn’t the same out of date rehashed material. Fantastic read.
    python training in rajajinagar
    Python training in bangalore
    Python Online training in usa

    ReplyDelete
  32. We really feel very happy about the blog you have shared. the explanation is very clear and valuable information. it improves my development skill in SCN and checkpoints. please share the blog like this...

    Start your journey with RPA Course and get hands-on Experience with 100% Placement assistance from Expert Trainers with 8+ Years of experience @eTechno Soft Solutions Located in BTM Layout Bangalore.

    ReplyDelete
  33. Thank you for sharing your awesome and valuable article this is the best blog for the students they can also learn.
    https://lookobeauty.com/best-interior-designer-in-gurgaon/

    ReplyDelete