Jump to content

rearrange input date from dd.mm.yyyy to yyyy.mm.dd


phingoc

Recommended Posts

Irrespective of the language used, the best (easiest for the user) way to handle date input by users is to use a jQuery datepicker with <select> fields enclosed in <noscript></noscript> tags for the users who don't allow javascript. The second best way is to use only <select> fields. It wouldn't take much work to change your form and processing code for them, just concatenate the values into the YYYY-MM-DD format for insert into the DB.

 

Whether you decide to implement a jQuery solution or not, the <select> fields are easy to generate dynamically, and help constrain the user to the proper format. I usually try not to just post a ready made solution, but I keep this code stored as a snippet that I use often anyhow. If you want to use it, feel free to do so.

 

<?php

// build day field
$curday = date('d');
echo "<select name=\"day\">\n";
for( $i = 1; $i < 32; $i++ ) {
   $sel = $curday == $i ? $sel = 'selected="selected"' : '';
   echo "<option value=\"$i\" $sel>$i</option>\n";
}
echo "</select>\n\n";

// build month field
$month = array( 1 => 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'); // display format is set when value is echoed
$curmonth = date('m');
echo "<select name=\"month\">\n";
foreach( $month as $k => $v ) {
   $sel = $k == $curmonth ? 'selected="selected"' : '';
   echo "<option value=\"$k\" $sel>" . ucfirst(substr($v, 0, 3)) . "</option>\n"; // Display format is set in this line using ucfirst and substr . . .
}
echo "</select>\n\n";

// build year field
$curyear = date('Y');
$yr_begin = $curyear - 100; // starts list from 100 years ago
$yr_end = $curyear + 0; // ends list at current year
echo "<select name=\"year\">\n";
for( $i = $yr_end; $i >= $yr_begin; $i-- ) {
   $sel = $i == $curyear ? 'selected="selected"' : '';
   echo "<option value=\"$i\" $sel>$i</option>\n";
}
echo "</select>\n\n";

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.