Home » Php » javascript – How to insert moment JS time into MySQL

javascript – How to insert moment JS time into MySQL

Posted by: admin April 23, 2020 Leave a comment

Questions:
//In Node/JS
myDate = moment(data.myTime.format('YYYY/MM/DD HH:MM:SS')).toISOString();
//myDate shows '2014-09-24T04:09:00.000Z'

Insert INTO (dateColumn..) Values(myDate)...

This is the error I get after inserting, note column in Mysql is a “datetime” type.

MySQL Error:: { [Error: ER_TRUNCATED_WRONG_VALUE: Incorrect datetime value: ‘2014-09- 24T04:09:00.000Z’ for column ‘_dateColumn’ at row 1] code: ‘ER_TRUNCATED_WRONG_VALUE’,

How to&Answers:

This result happens because you are using the toISOString() method and it is not a valid format to insert into your DATETIME column. The correct format probably is YYYY-MM-DD HH:MM:SS(I think it depends on MySQL configuration, but this is the default) as the docs points out.

So you should try using moment’s format() method like this:

myDate =  moment(data.myTime.format('YYYY/MM/DD HH:mm:ss')).format("YYYY-MM-DD HH:mm:ss");

In fact, I don’t know what data.myTime is, but if its a moment object too, you can change the first format() method and remove the second one.

Answer:

DontVoteMeDown answer is right, except that the minutes 'mm' and seconds 'ss' need to be in lowercase, otherwise a wrong value is returned:

myDate =  moment(new Date()).format("YYYY-MM-DD HH:mm:ss");

Also, you should check the value sent by javascript before to do your SQL query, in PHP:

DateTime::createFromFormat('Y-m-d H:i:s', $myDate);

Will return false if the date is misformatted.

Answer:

Here’s a function extension to format it into the MySQL DateTime format

moment.prototype.toMySqlDateTime = function () {
    return this.format('YYYY-MM-DD HH:mm:ss');
};

You’ll be able to do: moment().toMySqlDateTime();

Answer:

To generate mysql format datetime you can use this:

var moment = require('moment');
let currentTimestamp = moment().unix();//in seconds
let currentDatetime = moment(currentTimestamp*1000).format("YYYY-MM-DD HH:mm:ss");//mysql datetime.
currentTimestamp = moment(currentDatetime).valueOf();//current timestamp in milliseconds

Answer:

(I’m working with Node.js, Express and MySql and this has worked for me:)

var momentDate=new moment('2018-08-31T20:13:00.000Z');
var readyToInsert=momentDate.format("YYYY-MM-DD HH:mm:ss");

Answer:

moment().format("YYYY-MM-DD HH:mm:ss")

Answer:

I think this is the correct format. Otherwise you get the months inserted in your minutes, and you also get seconds above 60.

myDate =  moment(data.myTime.format('YYYY/MM/DD HH:MM:ss')).format("YYYY-MM-DD HH:MM:SS");

Tested in Chrome with Moment.js 2.9.0