CSV Import to Mysql

CSV Import to Mysql

bradAbradA Posts: 1Questions: 1Answers: 0

Hi

I need to import a CSV containing a date column which is is UK format d-m-Y.
I would like my code to change the format to Y-m-d before inserting into Mysql database.
At the moment I have the following which does change the format it's changing all the date values to the same date.

    ->on( 'preCreate', function ( $editor, $values ) {
        $date = date('Y-m-d',strtotime($values['date']));
        $editor
        ->field( 'date' )
        ->setValue( $date );
    } )

Could you please let me know how I would be able to loop through all the dates.

Thanks

Answers

  • allanallan Posts: 63,214Questions: 1Answers: 10,415 Site admin

    Rather than using an event handler to do this, use a set formatter. That is a function that will transform what is submitted from the client to whatever the database needs. We have built in formatters for date / time.

    For example in this case you might use:

    Field::inst('date')
      ->setFormatter( Format::dateSqlToFormat('d-m-Y-') )
    

    You probably want a get formatter similar to that (see the example on the doc page above) for displaying the table.

    Regards,
    Allan

This discussion has been closed.