5

I have date picker in my application. I want to insert the selected date into a MySQL database column with DATETIME data type.

This is the value of the date picker in Angular using console.log(date.value) :

Tue Nov 12 2019 00:00:00 GMT+0200 (Israel Standard Time)

Which format does the date need to be converted to for MySQL database insertion?

2 Answers 2

6

To ensure consistency, it is helpful to store all dates in the UTC timezone.

Step 1: Convert JavaScript Date to ISO (UTC timezone)

const isoDateString: string = datePickerDate.toISOString();

This also enables sending the date via JSON to the server.

Step 2: Ensure that MySQL timezone is UTC

cursor.execute("SET time_zone = '+00:00'")

Step 3: Format date for MySQL insertion

On the Node.js server, parse the ISO date string (from step 1) and format as:
'YYYY-MM-DD HH:MM:SS'

const isoDate = new Date(isoDateString);
const mySQLDateString = isoDate.toJSON().slice(0, 19).replace('T', ' ');

MySQL Documentation

MySQL recognizes DATETIME and TIMESTAMP values in these formats:

As a string in either 'YYYY-MM-DD HH:MM:SS' or 'YY-MM-DD HH:MM:SS' format. A “relaxed” syntax is permitted here, too: Any punctuation character may be used as the delimiter between date parts or time parts. For example, '2012-12-31 11:30:45', '2012^12^31 11+30+45', '2012/12/31 11*30*45', and '2012@12@31 11^30^45' are equivalent.

The only delimiter recognized between a date and time part and a fractional seconds part is the decimal point.

The date and time parts can be separated by T rather than a space. For example, '2012-12-31 11:30:45' '2012-12-31T11:30:45' are equivalent.

As a string with no delimiters in either 'YYYYMMDDHHMMSS' or 'YYMMDDHHMMSS' format, provided that the string makes sense as a date. For example, '20070523091528' and '070523091528' are interpreted as '2007-05-23 09:15:28', but '071122129015' is illegal (it has a nonsensical minute part) and becomes '0000-00-00 00:00:00'.

As a number in either YYYYMMDDHHMMSS or YYMMDDHHMMSS format, provided that the number makes sense as a date. For example, 19830905132800 and 830905132800 are interpreted as '1983-09-05 13:28:00'.

Sign up to request clarification or add additional context in comments.

Comments

0

you can use this:{{yourDate | date: 'yyy-MM-dd HH:MM:SS'}} then send it to controller and then save into db

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.