开发者

Simply convert this date into the right format

I have a date I need to store in a date field in mysql. My string is in the following format:

24/02/2011

While it needs to get into the database as:

2011-02-24

I thought I would be able to do it like so in the sql query

STR_TO_DATE('.$_POST['start_d开发者_Go百科ate'].', \'%d,%m,%Y\')

But it doesn't like it.

Is there another method?


$parts = explode("/", $date);
$date = $parts[2] . '-' . $parts[1] . '-' . $parts[0];


Your format appears to be wrong. In your string, the parts are separated by slashes, not commas. So, try this:

STR_TO_DATE('.$_POST['start_date'].', \'%d/%m/%Y\')

Alternatively, use PHP:

$ary = strptime($date_string, '%d/%m/%Y');
$mysql_date = sprintf('%s-%s-%s', $ary['tm_year'], $ary['tm_mon'], $ary['tm_mday']);


or you can use

$dob1=trim($_POST['txt_dob']);//$dob1='dd/mm/yyyy' format
list($d, $m, $y) = explode('/', $dob1);
$mk=mktime(0, 0, 0, $m, $d, $y);
$dob_disp1=strftime('%Y-%m-%d',$mk);


You could solve this in PHP by simply doing:

$date = date('Y-m-d', strtotime($_POST['start_date']));

I would instead recommending storing it as a timestamp, and let your presentation layer handle this logic, it should not be a concern of your database to know how to present a date.


Try to share my solution here (but maybe this is not the effective way but its work for me) Usually before posting date value to mysql i do some validation first using php function to check whether the date is correct value/format or not and then reformatted the date to conform mysql date value format.

here is my function

function prepareDate($value) {
    if (preg_match ( "/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/", $value, $regs )) {
        $date = "$regs[3]-$regs[2]-$regs[1]";
    } else {
        if ($value === '') {
            $date = null;
        } else {
            throw new Exception ( "Invalid date format: $value" );
        }
    }
    return $date;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜