I have the following trigger which inserts records into Table B whenever Table A is updated. This works fine however TableA_date is in unix time format and I want to convert it when the trigger inserts the record in Table B.
DELIMITER $$
CREATE TRIGGER MyTrigger
AFTER INSERT
ON TableA
FOR EACH ROW
BEGIN
INSERT INTO TableB SET
TableB_id = NEW.TableA_id,
TableB_date = FROM_UNIXTIME(NEW.TableA_date, '%d/%m/%y %r'),
TableB_comment = NEW.TableA_comment;
END $$
DELIMITER ;
In my results, instead of “01/01/70 03:00:05 AM” as the converted date I get “5” – I know the format string is correct as I am able to use it in a select statement. Thanks for your help
You are working too hard. Just leave out the format string entirely. Dates are stored as dates, not a strings.
In fact, don’t even use the conversion at all! Just directly assign the date column, and MySQL will do any conversion it needs.
I’m assuming that TableA_date is stored using the
timestampdatatype, and that TableB_date isdatetime. (Although you may wanttimestampfor that one too.)If you are using other datatypes like int, or char, then fix it. That’s not the correct way to structure a database.
Just to answer your actual question (instead of telling you the correct way to do it) the date format you want is
yyyy-mm-dd hh:mm:ssnot what you have.