Jump to content

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


phingoc

Recommended Posts

Are the submitted dates coming from a user submitted form? How are the users inputting the dates, with <select> fields, or something else?

 

Formatting the dates for display can be easily done with the DATE_FORMAT() function in MySQL.

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";

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.