Welcome Guest, Not a member yet? Register   Sign In
alter_date function
#1

[eluser]xwero[/eluser]
One of my problems with the validation library is that allows developers to alter $_POST values. That is why i'm working on a method that puts the $_POST alterations in the library where it belongs to namely the input library.

One of the functions i currently needed was altering a date and i wanted to share it with you because i'm going to release the input method with an upgrade of the validate library.
Code:
function alter_date($value,$from,$to,$locale=NULL)
{
    preg_match('/\D/',trim($value),$valueseparator);
    preg_match('/[a-z]+/i',trim($value),$words);
    if(is_string($locale) && count($words) == 1)
    {
        setlocale(LC_TIME, $locale);
        for($i =1;$i<13;$i++)
        {
            if(strftime("%b",mktime(0, 0, 0, $i, 1, 2000)) == $words[0] || strftime("%B",mktime(0, 0, 0, $i, 1, 2000)) == $words[0])
            {
                $value = str_replace($words[0],$i,$value);
            }
        }
    }
    
    $valuearr = explode($valueseparator[0],$value);
    preg_match('/\W/',$from,$fromseparator);
    $fromarray = explode($fromseparator[0],strtolower($from));
    $d = $valuearr[array_search('d',$fromarray)];
    $m = $valuearr[array_search('m',$fromarray)];
    $y = $valuearr[array_search('y',$fromarray)];
    
    return date($to,mktime(0, 0, 0, $m, $d, $y));
}

For English dates there is strtotime but if the date format isn't right or if there are non English words in it the function isn't useful anymore.

Examples
Code:
$date1 = '1-1-2008';
echo alter_date($date1,'d-m-Y','Y-m-d');
// gives 2008-01-01

$date2 = '1 jan 2008';
echo alter_date($date2,'d-m-Y','Y-m-d');
// gives 2008-01-01

$date1 = '1 mei 2008';
echo alter_date($date1,'d-m-Y','Y-m-d','nl_NL');
// gives 2008-05-01

A modification is that you replace the date function with the strftime function. But i made the function with database insertion in mind.




Theme © iAndrew 2016 - Forum software by © MyBB