Hi all,

I have searched the forum for an answer to this post without finding what I am looking for. I am using Smarty template engine.

I have a form with a date field and I want to force the user to enter the date in the correct format, ie "10/07.07".

The field code in the form is:

<input  type="text" name="departuredate" id="departuredate" class="bodytext"
value="{$user.departuredate|escape}" size="12" />

I am storing the date in my SQL database as a string, this may not be correct.

Can anyone please advise.

    The surest way is to provide 3 select drop-downs, one for each part(year, month, day). Then take those separate values and format/concatenate them as needed for your database's date string format. You can use PHP's [man]checkdate/man function to verify that the values are valid.

      Hi and thank you for your reply.

      I do appreciate what you have said and I know you are correct in the way to force the input.

      It looks and sounds a lot of coding just to force the input of "d/m/y". Is there a way to display "d/m/y" in the field when it is displayed.

        <input type="text" name="date" value="dd/mm/yyyy" size="10" maxlength="10">
        

        And yes, it takes a couple more minutes to code in the separate select elements, but it can save a lot of confusion, such as when a user types in "10/12/2007" and you can't be 100% sure whether s/he meant Oct. 12 or the 10th of December. And if you accept 2-digit years, you multiply the possible confusion. (And you can save quite a bit of typing by using PHP for loops to create the option elements for each select.)

          dcjones,

          I am a newb to this forum but, I am not a newb to PHP/MySQL. Let me first address some of your questions:

          1) Storing the date as a string. This is fine as it will not break anything and MySQL actually stores dates as strings. Now, there are some advantages to using dates. 1) It forces a date format. If somehow, the user gets some text by you, then, it can make it into the DB. With a date field, MySQL will try and make sense of it all but ultimately if it can not, it will put something in the YYYY-MM-DD format. another advantage is the use of date functions. There are a ton of them, shame to loose out on them. Lastly, searching on date ranges may not work correctly if you can not ensure the proper format in the db. Maybe 1 screen allows mm-dd-yyyy and another yyyy-mm-dd. Well, if you search on the date, one will work and the other wont.

          phew, long and short of it, use dates.

          now, lets say MySQL stores the date as YYYY-MM-DD and you want to display it in MM/DD/YY format for the user, then use the smarty date_format modifier like so:

          value="{$user.departuredate|date_format:'%m/%d/%y'}"
          

          Lastly as far as how to ensure the user enters a know format. I do this.

          1) Make a readonly input box:

          <input type="text" name="myDate" id="myDate" value="" size="10" readonly="readonly">
          

          2) use a date picking application (I use SCW - simple calendar widget (http://www.garrett.nildram.co.uk/calendar/scw.htm - it is the bomb yo!). Then have the calendar widget change value of the input. This way, the user never enters a date and you can configure what format you want ( and there is not any problems mentioned before with the 10/12/07 problems, etc.)

          3) Setup the server side to pick apart the date and convert to MySQL format. There are so many ways to do this, you could use strtotime (my favorite and real powerful). I happen to have a date class that uses strtotime and then stores the date as a Unix timestamp, then you can call $objDate->mGetFormattedDate( "Y-m-d') which just calls the date function against the stored timestamp. I can post code if you really want to see it. I call it cUniDate.

          Hope this helps.

          Mike

            Good morning Mike.

            Your reply is one of the most well written answers I have seen here at PHP builder.

            I am going to follow your example, it sounds that this is exactly what I need.

            Your offer of the code is of great interest and would appreicate a copy.

            Many thanks.

              dcjones,

              Here is the Date Class:

              <?php
              /* vim: set expandtab tabstop=4 shiftwidth=4: */
              
              // +----------------------------------------------------------------------+
              // | $Workfile: cUniDate.class.php $
              // +----------------------------------------------------------------------+
              // | PHP version 5
              // +----------------------------------------------------------------------+
              
              // $Id: $
              
              //-------------------------------------------------------------------------
              /**
              * Dependencies 
              */
              //-------------------------------------------------------------------------
              
              /**
              * Handles Dates. Takes a Date input, transforms it to a timestamp and 
              * then allows you to get the date back out in any php::date() format
              *
              * <code>
              *	try
              *	{
              *		$objUni = new cUniDate();
              *		$objUni->mSetDate( '04/04/04' );
              *		$strDate = $objUni->mFormatDate( 'Y-m-d' );		// returns "2004-04-04"
              *	}
              *	catch( Exception $objE )
              *	{
              *		echo $objE->getMessage();
              *	}
              * </code>
              *
              * @version		$Revision: 3 $
              * @package		Library
              * @author		Michael B
              * @since		5.1.2
              * @see			
              */
              class cUniDate 
              {
              	/**
              	* Integer TimeStamp
              	*
              	* @var		integer
              	* @access	protected
              	*/
              	protected $_intTimeStamp;
              
              /**
              * Sets the Date string in the object
              *
              * @access	public
              * @author	Michael B
              *
              * @param	string $strdate
              * @return	void
              */
              public function mSetDate( $strDate )
              {
              	$this->_intTimeStamp = $this->_mParseDate( $strDate );
              }
              
              
              /**
              * returns a formated date
              *
              * @access	public
              * @author	Michael B
              *
              * @param	string $strFormat
              * @return	void
              */
              public function mFormatDate( $strFormat )
              {
              	if ( $this->_intTimeStamp !== null )
              	{
              		return date( $strFormat, $this->_intTimeStamp );	
              	}
              
              	throw new Exception( basename(__FILE__) . '::mFormatDate ('.__LINE__.') ERROR: Can not call mFormatDate() before mSetDate()!' );
              }
              
              
              /**
              * Parses a Date and converts it to a timestamp format. Note
              * that stringtotime seems to choke on dates with dashes
              * so I added some preg matching to catch this case.
              *
              * @access	protected
              * @author	Michael B
              *
              * @param	string $strDate
              * @return	string
              */
              protected function _mParseDate( $strDate )
              {
              	// Mysql Format: YYYY-MM-DD
              	if ( preg_match( '/\d{4}-\d{2}-\d{2}/', $strDate ) )
              	{
              		$arrPieces = explode( '-', $strDate );
              		return mktime( 1, 0, 0, $arrPieces[1], $arrPieces[2], $arrPieces[0] );
              	}
              
              	// MM-DD-YYYY
              	elseif ( preg_match( '/\d{1,2}-\d{1,2}-\d{4}/', $strDate ) )
              	{
              		$arrPieces = explode( '-', $strDate );
              		return mktime( 1, 0, 0, $arrPieces[0], $arrPieces[1], $arrPieces[2] );
              	}
              
              	// MM-DD-YY
              	elseif ( preg_match( '/\d{1,2}-\d{1,2}-\d{2}/', $strDate ) )
              	{
              		$arrPieces = explode( '-', $strDate );
              		$strCentury = substr( date( 'Y' ) , 0, 2 );
              		return mktime( 1, 0, 0, $arrPieces[0], $arrPieces[1], $strCentury . $arrPieces[2] );
              	}
              
              	// Try strtotime():
              	elseif ( $strTimeStamp = strtotime( $strDate ) )
              	{
              		return $strTimeStamp;
              	}
              
              	else 
              	{
              		return mktime();
              	}
              }
              }
              ?>
              

              This is the class. The example usage is in the comments on the top. Hope it helps. Please give me credit for the code where ever you use it. Please note. This class will only work in PHP5. You will need to make some modifications to get it to work in PHP4.

              -Michael

                Write a Reply...