STR_TO_DATE returns null - mysql

I'm trying to convert a string to date with a format of yyyy/mm to yyyy
STR_TO_DATE(SUBSTRING(time,1,4), '%Y')
This returns null for every value as well as when I try to convert without getting rid of the mm:
STR_TO_DATE(REPLACE(time,'/',''), '%Y%m')
This method has worked for me before, I'm at a loss for what I'm missing.
Thanks in advance!
Edit for clarification:
Eventually I am going to insert the year into a column with data type year, so I need to convert a varchar to a date type so I can extract the year in order to insert the data into a new table
I am in the process of making sure it will work before populating the new column with a command like this:
INSERT INTO table (year)
SELECT STR_TO_DATE(SUBSTRING(time,1,4), '%Y')
FROM `origtable`

I'm trying to convert a string to date with a format of yyyy/mm to yyyy
Just use left():
select left(time, 4) as yyyy
There is no need to convert to a date or datetime. You want a simple string operation.
EDIT:
year is a really weird type. I would just use an integer. But if you are using it, you can insert a full date into the field:
select date(concat(time, '/01'))
The resulting date can be inserting to a year column.

Related

Date conversion query in SQL using STR_TO_DATE

In my table, there is a date column i.e. ORDER DATE which is in dd-mm-yyyy format, and the datatype of this date column is text. Now, I want to convert the format from yyyy-mm-dd. But the date format is not changing at all. Trying to use STR_TO_DATE but the year in the dates are coming as 2020 only. Not sure how to fix it or if there is a better way to convert the date in MySQL.
For example:
SELECT STR_TO_DATE('14-09-2017','%d-%m-%y') AS DATE;
Result coming as 2020-09-14
Or suppose
SELECT STR_TO_DATE('20-MAR-2018','%d-%b-%y') AS DATE;
Result coming as 2020-03-20
day and month are coming properly but the year is not coming. Kindly help how to get convert the date format correctly.
Try to change your command like this below and you will get the answer:
SELECT STR_TO_DATE('14-09-2017','%d-%m-%Y') AS DATE;
Refer to the documentation for more info about the commands.

MySQL convert timestamp and time string to DateTime format

In my table have two columns, one as timestamp to save the date and one as time string to save the time with period.
Eg:
I want to combine them into one column as DateTime format in the result then order by desc on that column.
Here is the example: http://sqlfiddle.com/#!9/25eb21/4
The column name 'Datetime' expected is Datetime or timestamps type, so I can sort correctly on it.
You do not need to convert the values to integers to add them. MySQL has built-in functions for this purpose:
SELECT *,
addtime(apptDate, str_to_date(apptTime, '%h:%i %p')) as datetime
FROM appt
ORDER BY Datetime DESC;
If apptTime is just a time value (which it should be), then you obviously do not need to convert from a string. I would usuggest fixing the data model.
Let me assume that you want to add the duration that is stored as a string in column apptTime to timestamp in column apptDate.
A typical approach uses str_to_date() to turn the string to a datetime, then converts the time portion to seconds using time_to_sec(), which we can then add to the timestamp using date artihmetics.
So
select t.*
apptdate
+ interval time_to_sec(str_to_date(appttime, '%h:%i %p')) second
as newapptdate
from mytable
select addtime(appDate, appTime) from ...
Your appDate contains a time, probably because you are applying a timezone. Either convert your two columns to the timezone your data is supposed to be in with convert_tz(), or extract the date part of it with date(appDate) before you add it. It wasn't clear which of the columns was a string, but extract() or str_to_date() is the way to parse a text into a date and/or time.

how to change date format in mysql

The default date format in my SQL is : '2019-05-06'
and its fine but when i insert date to my table i want this format 2019-5-6 not the above format
It means month and day must be start 1 to 30 not 01 to 31.Is there any way to change default format in my sql?
You seem to be looking for the MySQL STR_TO_DATE function :
It takes a string str and a format string format. STR_TO_DATE() returns a DATETIME value if the format string contains both date and time parts, or a DATE or TIME value if the string contains only date or time parts.
So if the date coming out of your application is like '2019-5-6', to convert it to a MySQL date you need :
STR_TO_DATE('2019-5-6', '%Y-%c-%e')
In an INSERT statement :
INSERT INTO mytable VALUES(1, STR_TO_DATE('2019-5-6', '%Y-%c-%e'));
Tip :
%Y : Year as a numeric, 4-digit value
%c : numeric month name (0 to 12)
%e: day of the month as a numeric value (0 to 31)
The default way to store a date in a MySQL database is by using DATE. The proper format of a DATE is: YYYY-MM-DD. If you try to enter a date in a format other than the Year-Month-Day format, it might work but it won't be storing the dates as you expect.
In order to run a MySQL Insert command and add the current date into your table you can use MySQL's built-in function CURDATE() in your query.
An example of how to Insert a Date in MySQL using CURDATE
$query_auto = "INSERT INTO tablename (col_name, col_date) VALUE ('DATE: Auto CURDATE()', CURDATE() )";
Also, you can run a query to set the date manually
An example of how to Insert a Date in MySQL manually
$query_manual = "INSERT INTO tablename (col_name, col_date) VALUES ('DATE: Manual Date', '2008-7-04')";
It is recommended to do the date formatting when doing a query, like so:
SELECT DATE_FORMAT(BirthDate, "%W %M %e %Y") FROM Employees;
You can find more examples of formatting the date here:
https://www.w3schools.com/sql/func_mysql_date_format.asp

How to convert text datatype to datetime in mysql?

In mysql database,column name created.This "created " column is text datatype,I need to change this to datetime.Now this column have so many datas.Is it possible to convert it or?
Database look like
created
18-11-15 18:21:25
Expecting ouput is
created
2018-11-15 18:21:25
When am doing
ALTER TABLE invoices MODIFY created datetime
This query giving wrong data.its converting from 15-09-18 03:03:43 to 2015-09-18 03:03:43
If the original data is not in MySQL Datetime format (YYYY-MM-DD HH:MM:SS), you cannot just change the column datatype from Varchar/Text to Date/Datetime. Otherwise, there will be an irreparable Data loss.
This will be a multi-step process. You will first need to convert the date string to MySQL date format (YYYY-MM-DD HH:MM:SS). We can use STR_TO_DATE() function for this.
Your sample date string (18-11-15 18:21:25) is basically in %y-%m-%d %T format. Following format specifiers can be used:
%d Day of the month as a numeric value (01 to 31)
%m Month name as a numeric value (00 to 12)
%y Year as a numeric, 2-digit value
%T Time in 24 hour format (hh:mm:ss)
The query to update the date would look as follows:
UPDATE invoices
SET created = STR_TO_DATE(created, '%y-%m-%d %T');
Now, you can use Alter Table to change the data type from Text type to Datetime.
ALTER TABLE invoices
MODIFY COLUMN created datetime;
The best thing to do here is to not store your dates as text. Assuming you have already done this, we can cope by calling STR_TO_DATE to generate a bona fide date:
SELECT
STR_TO_DATE(created, '%y-%m-%d %h:%i:%s') AS created_out
FROM yourTable;
Since the output you expect is standard date output, we can stop here and avoid also calling DATE_FORMAT to generate a different output.
you want to convert output or database records ? for second you can use sql query :
UPDATE 'table_name' SET 'created' = CONCAT('20', 'created')
You will need first to interchange the day with the year in the created column, as follows:
UPDATE invoices
SET created = CONCAT(SUBSTR(created, 7, 2), '-', SUBSTR(created, 4, 2), '-', SUBSTR(created, 1, 2));
Then, you convert the column to DATETIME, as follows:
ALTER TABLE invoices MODIFY created DATETIME;
Hope this helps.

Cannot scan the right values of Order date in sql

I want to fetch all datas that corresponds in the chosen date range.
So the problem is that. When theres included time in the data. It can't fetch the required data to be displayed. But when I remove the time on it. It displays really well. What can I do to make it right?
EXAMPLE VALUES:
2018-10-29 01:21:29pm
2018-10-30 01:21:29pm
EXAMPLE VALUES THAT WORKS:
2018-10-29
2018-10-30
My query:
`"SELECT *,SUBSTRING(order_date,1,10) from orders where order_date >='$fromdate' AND order_date <='$todate'"`
Ideal Solution: You will need to change the datatype of order_date from Varchar(500) to Datetime type, using Alter Table command.
Now, it is noteworthy that the MySQL datetime value is in YYYY-MM-DD HH:MM:SS format. So firstly, you will need to change your datetime string to MySQL datetime format string. Otherwise, directly changing the datatype will lead to irreparable loss/truncation of data.
Your datetime value 2018-10-29 01:21:29pm is basically of YYYY-MM-DD HH:MM:SS AM/PM (12 hour format). In terms of format specifiers, it would be: '%Y-%m-%d %h:%i:%s%p'. Complete list of available format specifiers can be seen in MySQL docs.
Firstly, we use Str_To_Date() function to convert all your data into proper Datetime format.
UPDATE orders
SET order_date = STR_TO_DATE(order_date, '%Y-%m-%d %h:%i:%s%p');
Now, next step is simple. Just modify the datatype to datetime:
ALTER TABLE orders
MODIFY COLUMN order_date datetime;