开发者

Convert user input to my date format

User ent开发者_运维问答ers the date as 8/1/11 or 08/1/11. Regardless of how the user inputs the date in my text field, I want to convert what they enter to my format of mm/dd/yyyy

So if the user enters 8/1/11 it would convert it to 08/01/2011.


Use strtotime() to transfer it into a time value, and then mktime() to transfer it to whatever format you want.

EDIT: Turns out it's not that simple.

You can't just print any date you'd like and transfer it to another, it'll be best to use some sort of UI on the client side to ensure the input matches, a great example is jQueryUI Datepicker


Check this. It also checks if the date is valid (with checkdate) and converts years from short to long. When using short years, 0-69 is converted to 2000-2069 and 70-99 is converted to 1970-1999.

<?php
function cleanDate($input)
{
    $parts = explode('/', $input);
    if(count($parts) != 3) return false;

    $month = (int)$parts[0];
    $day = (int)$parts[1];
    $year = (int)$parts[2];

    if($year < 100)
    {
        if($year < 70)
        {
            $year += 2000;
        }
        else
        {
            $year += 1900;
        }
    }

    if(!checkdate($month, $day, $year)) return false;

    return sprintf('%02d/%02d/%d', $month, $day, $year);
    // OR
    $time = mktime(0, 0, 0, $month, $day, $year);
    return date('m/d/Y', $time);
}

$test = array(
    '08/01/2011', '8/1/11', '08/01/11', // Should all return 08/01/2011
    '08/1/87', // Should return 08/01/1987
    '32/1/93', '13', // Should fail: invalid dates
    '02/29/2011', // Should fail: 2011 is not a leap year
    '2/29/08'); // Should return 02/29/2008 (2008 is a leap year)
foreach($test as $t)
{
    echo $t.' : '.(cleanDate($t) ?: 'false')."\n";
}
?>

Result:
08/01/2011 : 08/01/2011
8/1/11 : 08/01/2011
08/01/11 : 08/01/2011
08/1/87 : 08/01/1987
32/1/93 : false
13 : false
02/29/2011 : false
2/29/08 : 02/29/2008


<?php

$userInput = '08/1/11';  // or = '8/1/11' or  = '08/01/11' or = '01/8/11'

$arr = explode('/', $userInput);

$formatted = sprintf("%1$02d", $arr[0]) . '/' . sprintf("%1$02d", $arr[1]) . '/20' . $arr[2];

?>


<?php
preg_match('#^(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])/(\d{2})$#',trim($date),$matches);
$month=str_pad($matches[1],2,'0',STR_PAD_LEFT);
$day=str_pad($matches[2],2,'0',STR_PAD_LEFT);
$year=$matches[3];

$result="{$month}/{$day}/{$year}";
?>


While @Truth is right that the user can do a lot to make it difficult, there IS actually a way to do a fairly decent job of parsing a date input box to work. It takes into account a variety of user input issues that may come up.

Note that it does make two assumptions:

That the local uses a date format of m/d/y
If the year is entered in short form, we are dealing with a 2000+ year

<?php  
    // Trim spaces from beginning/end  
    $date = trim(request($field));  
    // Allow for the user to have separated by spaces  
    $date = str_replace(" ", "/", $date);  
    // Allow for the user to have separated by dashes or periods  
    $date = str_replace("-", "/", str_replace(".", "/", trim($date)));  
    // Explode the date parts out to ensure a year  
    // Granted, this is geo-centric - you could adjust based on your locale  
    $dateparts = explode("/", $date);  
    // Check for a year.  If not entered, assume this year  
    if (!isset($dateparts[2])) {$dateparts[2] = date("Y");}  
    // Force year to integer for comparison  
    $dateparts[2] = (int)$dateparts[2];  
    // Allow for user to use short year.  Assumes all dates will be in the year 2000+  
    if ($dateparts[2] < 2000) {$dateparts[2]+= 2000;}  
    // Re-assemble the date to a string  
    $date = implode("/", $dateparts);    
    // Utilize strtotime and date to convert date to standard format  
    $date = date("m/d/Y", strtotime($date));
?>

Disclaimer: Yes, this is the verbose way of doing this, however I did so for clarity of the example, not for efficiency.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜