|
Posted by Erwin Moller on 04/25/06 11:08
windandwaves wrote:
> Hi Folk
>
> I love the strtotime function, because I can make a date field in a form
> and just tell my users to enter whatever they want and as long as it is a
> date, it will work.
>
> HOWEVER, this obviously does not work for the day/month vs month/day
> scenario. That is, in New Zealand we use day/month/year, while the
> function assumes it to be month/day/year.
And that's a pain, isn't it?
I always solve this problem in one of the following ways:
1) Ask the user 3 inputfields, day/month/year, or whatever order is
appropriate in some country.
2) Make my own datestring for the database-insert, or make my own date for
PHP purposes, which is easy once you know what field is what.
Alernatively, if you want to offer your visitor ONE field for a date, just
make sure YOU parse it the way it should be before using.
eg:
[html]
format: d/m/y
<input type="text" name="somedate">
[php]
$dateparts = split("/",$_POST["somedate"]);
// now reasssemble any way you want: eg:
DateForPostgres = $dateparts[1]."/"$dateparts[0]."/".$dateparts[2];
(assuming Postgres is set to take m/d/y dates.)
Regards,
Erwin Moller
>
> Does anyone have a simple function that helps me close that loophole (I am
> using PHP 4.4).
>
> I copied the function below from php.net, but I dont think it will work in
> all cases.
>
> Cheers
>
>> Nicolaas
> # Returns a timestamp from a string based on the given format and default
> timezone if it's ambiguous.
> # %Y - year as a decimal number including the century
> # %m - month as a decimal number (range 01 to 12)
> # %d - day of the month as a decimal number (range 01 to 31)
> # %H - hour as a decimal number using a 24-hour clock (range 00 to 23)
> # %M - minute as a decimal number
>
> function parseDate( $date, $format = "%d/%m/%Y") {
> // Builds up date pattern from the given $format, keeping delimiters in
> place.
> if( !preg_match_all( "/%([YmdHMp])([^%])*/", $format, $formatTokens,
> PREG_SET_ORDER ) ) {
> return false;
> }
> foreach( $formatTokens as $formatToken ) {
> $delimiter = preg_quote( $formatToken[2], "/" );
> $datePattern .= "(.*)".$delimiter;
> }
>
> // Splits up the given $date
> if( !preg_match( "/".$datePattern."/", $date, $dateTokens) ) {
> return false;
> }
> $dateSegments = array();
> for($i = 0; $i < count($formatTokens); $i++) {
> $dateSegments[$formatTokens[$i][1]] = $dateTokens[$i+1];
> }
>
> // Reformats the given $date into US English date format, suitable for
> strtotime()
> if( $dateSegments["Y"] && $dateSegments["m"] && $dateSegments["d"] ) {
> $dateReformated =
> $dateSegments["Y"]."-".$dateSegments["m"]."-".$dateSegments["d"];
> }
> else {
> return false;
> }
> if( $dateSegments["H"] && $dateSegments["M"] ) {
> $dateReformated .= " ".$dateSegments["H"].":".$dateSegments["M"];
> }
>
> return strtotime( $dateReformated );
> }
Navigation:
[Reply to this message]
|