How to insert date into MySQL DATETIME column from Angular using Node.js? - mysql

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?

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'.

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

Related

MySQL equivalent of php's strtotime()

Is there a way to convert a string such as "-1 week" or "-5 minutes" into a datetime value in MySQL similar to php's extremely convenient strtotime() function?
I have a table that stores a human-readable time interval (such as "2 minutes") in one column and a datetime in another column.
I would like to select the rows where more than the amount of time specified in interval has elapsed since datetime.
MySQL doesn't have an equivalent of PHP's strtotime() in the sense that there is nothing that will automatically attempt to parse and determine the format of a date string using by assuming multiple formats.
What it does have is STR_TO_DATE(str,format) which requires you specify the format of your date, time or date + time string. It is the equivalent of PHP's date_create_from_format(format, str) function (though the format of the format parameter are different).
Here are some examples given from the MySQL documentation. They show a date being passed along with the format string that lets it know how the date string is to be interpreted:
SELECT STR_TO_DATE('01,5,2013','%d,%m,%Y');
SELECT STR_TO_DATE('May 1, 2013','%M %d,%Y');
Alternatively, you can cast a string to a date, time or datetime type, but they require a specific format (YYYY-MM-DD hh:mm:ss.fraction) for it to work:
SELECT CAST("2019-11-21" AS DATE);
If you deviate too far from that format it will make a few assumptions but could produce an incorrect date.

MySql not allow to insert full date in datetime field in version 5.7.*

Just want to change this via configuration only. without change my query
Current SQL_MODE is
STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
I have one table dummy_test and there is one field name created_at
created_at => datetime(NULL)
When i perform below query
insert into dummy_test values('2018-08-14 05:38:11 pm')
ITs give me an error
Error in query (1292): Incorrect datetime value: '2018-08-14 05:38:11 pm' for column 'created_at' at row 1
It's working fine with
insert into dummy_test values('2018-08-14 05:38:11')
Per MySQL documentation:
MySQL recognizes TIME values in these formats:
As a string in 'D HH:MM:SS' format. You can also use one of the following “relaxed” syntaxes: 'HH:MM:SS', 'HH:MM', 'D HH:MM', 'D HH', or 'SS'. Here D represents days and can have a value from 0 to 34.
As a string with no delimiters in 'HHMMSS' format, provided that it makes sense as a time. For example, '101112' is understood as '10:11:12', but '109712' is illegal (it has a nonsensical minute part) and becomes '00:00:00'.
As a number in HHMMSS format, provided that it makes sense as a time. For example, 101112 is understood as '10:11:12'. The following alternative formats are also understood: SS, MMSS, or HHMMSS.
So you'll have to use 24-hour time when sending to MySQL. If you're passing the date/time via PHP, this question might be helpful.
you can use STR_TO_DATE function
ie.. insert into dummy_test values(STR_TO_DATE('2018-08-14 05:38:11 PM', '%Y-%m-%d %h:%i:%s %p'))
If you want, you can add a "BeforeInsert" table trigger to intercept and convert those values.

Postgres: JSONB string to timestamp with TZ

In postgres database (9.4) i have data saved as JSON object. Including some datetime elements. In order to do time comparision in sql query I have to convert this string to timestamp. I have tried this query:
SELECT to_timestamp('2015-05-22T10:56:04.949Z','YYYY-MM-DD HH:MI:SS.MS');
-- dummy query just to test converting
OUTPUT: 2015-05-22 10:56:04.949+03
It works basically fine, except, I cant figure out how to include timezone parameter there. This string is in UTC time 10:56AM, if I run this query, I'll get 10:56 in +03 timezone (+03 is my local timezone). According to Postgres documentation, TZ should be added to format string to get timezone as well, but it does not work.
How to format this string so that it includes also timezone from initial date-time string ?
As far as I know it's not possible to parse timezone from string.
However if you know your timestamp is always in UTC timezone you can use:
SELECT to_timestamp('2015-05-22T10:56:04.949Z','YYYY-MM-DD HH:MI:SS.MS')::timestamp at time zone '00:00'

MySQL and datetime

If I have a table with a DATETIME column I can insert dates that have a format like:
2015-03-25 10:10:10
2015-03-25 10:10
2015-03-25 10
2015-03-25
It will fill in the remainder with zeros. I can't however use
2015-03
2015
As it will give an 'Incorrect datetime value' error. It is however possible to use these last two in a SELECT like [..] WHERE timestamp < '2015-03' ..
Is there a way that MySQL will fill in the remainder of datetimes with 01-01 for the month and day if omitted in datetimes or do I have to do that manually myself?
I.e. I would like to use '2015-03' in an INSERT statement, or do something like SELECT DATE_FORMAT('2015-03', '%Y%m%dT%H%i%S')
As stated in Date and Time Literals:
MySQL recognizes DATE values in these formats:
As a string in either 'YYYY-MM-DD' or 'YY-MM-DD' format. A “relaxed” syntax is permitted: Any punctuation character may be used as the delimiter between date parts. For example, '2012-12-31', '2012/12/31', '2012^12^31', and '2012#12#31' are equivalent.
As a string with no delimiters in either 'YYYYMMDD' or 'YYMMDD' format, provided that the string makes sense as a date. For example, '20070523' and '070523' are interpreted as '2007-05-23', but '071332' is illegal (it has nonsensical month and day parts) and becomes '0000-00-00'.
As a number in either YYYYMMDD or YYMMDD format, provided that the number makes sense as a date. For example, 19830905 and 830905 are interpreted as '1983-09-05'.
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'.
Notably, MySQL does not support the incomplete formats that you wish to use.
That MySQL happens to accept some of the incomplete formats you've tried (apparently by padding with zeroes) is undocumented behaviour, quite possibly unintended by the developers. It cannot (and should not) be relied upon, not least because edge cases could exist under which the behaviour breaks; or because the behaviour could be changed without warning in a future release.
If it's absolutely necessary to provide such incomplete temporal literals to MySQL (which it shouldn't be, as your data access layer ought to be aware of the type of values it is handling and provide them to MySQL in a supported format), you can use its STR_TO_DATE() function to parse them accordingly:
Unspecified date or time parts have a value of 0, so incompletely specified values in str produce a result with some or all parts set to 0:
mysql> SELECT STR_TO_DATE('abc','abc');
-> '0000-00-00'
mysql> SELECT STR_TO_DATE('9','%m');
-> '0000-09-00'
mysql> SELECT STR_TO_DATE('9','%s');
-> '00:00:09'
Range checking on the parts of date values is as described in Section 11.3.1, “The DATE, DATETIME, and TIMESTAMP Types”. This means, for example, that “zero” dates or dates with part values of 0 are permitted unless the SQL mode is set to disallow such values.
So, for example, you might use:
STR_TO_DATE('2015-03', '%Y-%m');
Try unix_timestamp()
SELECT like [..] WHERE unix_timestamp(timestamp) < '2015-03'

Convert varchar string data to time format in mysql

I need to convert varchar string data to time format in mysql.
For example,
I have a varchar column in table which stores time. The accepted values should be like 9:30 AM or 1200 PM. But currently it has either blank values or it has values like 9.30am or 12:00
There are many records like this, so cannot update manually.
Ithere any work around or function or procedure to do so?
please help.
Thanks
You can use the STR_TO_DATE() MySQL function to convert any string to a date.
Additionally you can use TIME() to extract the time portion of a datetime. A combination of both function is used to convert an arbitrary date string to a datetime and then you can extract the time portion from it as a valid MySQL TIME.
By default MySQL functions follow standard format but custom format can be specified and if your values don't use the international formats you'll need to check with the documentation and provide the format your system is using.