Date and time conversion query in SQL - mysql

In my database table, there is a date column i.e. EXPECTED DATE which is in dd-mm-yyyy format, and the datatype of the column is text. Now, I want to convert the format to yyyy-mm-dd. But the date is not changing at all and also when I tried to get the timestamp for the expected date column . I am getting some errors. For date coming I have used this STR_TO_DATE. But the year is not coming like what I expect and the timestamp also.
For example:
select STR_TO_DATE ('30-11-2011', '%d,%m,%y') as date ;
returns a result as
2020-11-30
And for timestamp
select STR_TO_DATE ('2011,11,30 12,30,45', '%y,%m,%d, %H,%I,%S');
I am not getting errors.
Please help me get the correct answers for this problem.

For the first query you need to use the %Y. Remember that it is always better to use "Y" for the years when you are writing a query for year.
SELECT STR_TO_DATE("30,11,2011", "%d,%m,%Y");
For the second one also, you can use '%Y' in the place of '%y'. For minutes, use '%i' not '%I'. For hours and minutes, you can use whatever you like.
SELECT STR_TO_DATE("2011,11,30 12,30,45", "%Y,%m,%d %h,%i,%s");
Refer to the below documentation for more clarification on SQL commands.

You need %Y (capital Y) for the 4 digit year, when using MySQL's STR_TO_DATE. Also, minutes is represented by %i, not %I, the latter which is hours on a 0 to 12 scale. So use:
SELECT STR_TO_DATE('30-11-2011', '%d-%m-%Y');
SELECT STR_TO_DATE('2011,11,30 12,30,45', '%Y,%m,%d %H,%i,%S');

For the first query you need to use the %Y'.
SELECT STR_TO_DATE("30,11,2011", "%d,%m,%Y");
For minutes, use this one only '%i'.
SELECT STR_TO_DATE("2011,11,30 12,30,45", "%Y,%m,%d %h,%i,%s");

Related

MySQL Query Group By Date

I have tried various recommendations based off of other posts with no avail.
I have a database scheme of records with a Created_Date Key, and Value would be 01/01/2017
I am trying to query the database records to give a returned count of How many records per month and which month those fall in line with.
With the following
SELECT SQL_NO_CACHE MONTH(`Created_Date`), COUNT(*)
FROM `CRM_Leads`
GROUP BY MONTH(`Created_Date`)
I return
MONTH(`Created_Date`) COUNT(*)
NULL 872
I have also tried almost all the variations on the following post
Count records for every month in a year
Any help would be appreciated.
assuming your created_date is a string of format ('dd-mm-yyyy') the you should convert as date with str_to_date
SELECT SQL_NO_CACHE MONTH(str_to_date(`Created_Date`, '%d/%m/%Y')), COUNT(*)
FROM `CRM_Leads`
GROUP BY MONTH(str_to_date(`Created_Date`, '%d/%m/%Y'))
For as long as you store date/time information as strings, you will have great difficulty using any date/time specific functions and features. If you are getting NULL from MONTH(str_to_date(Created_Date, '%d/%m/%Y')) then the str_to_date isn't converting the strings to dates and the most likely reason for this is the d m y "pattern" is not corrrect.
All you have old us about your "strings that might be dates" is that one of them looks like this: 01/01/2017. Now that could be DD/MM/YYYY or MM/DD/YYYY and we simply cannot tell which one is correct from the single value you have chosen to share with us. Look for any day value greater then 12 in your data e.g. 17/01/2017 ==> DD/MM/YYYY or 01/17/2017 ==> MM/DD/YYYY
Once you have made the choice of which pattern your "strings that might be dates" follow; apply that pattern in the str_to_date() function. You migh want to try a few different patterns to get the best one (and these are just 3 of many you could try):
# which pattern is best for you?
SELECT Created_Date
, str_to_date(`Created_Date`, '%d/%m/%Y') "d/m/y"
, str_to_date(`Created_Date`, '%m/%d/%Y') "m/d/y"
, str_to_date(`Created_Date`, '%Y-%m-%d') "y-m-d"
FROM `CRM_Leads`
You will not have success with your group by query until you choose the most appropriate d m y pattern to apply in teh str_to_date function. Note here that you might also have a variety of patterns in your data, in which case you have an even bigger problem to solve.
Once you have made the choice of which pattern your "strings that might be dates" follow; apply that pattern in the str_to_date() function and ONLY THEN your group by query will work.

MySQL query to search in between two time range between two dates using timestamp data

I have timestamp values in my db. It has values like 2014-11-25 10:30:00.
I need to get all records between two dates and that has time between certain range like between 2014-10-20 to 2014-11-25 and between 9am to 7pm..
I need the query for this...
You can use the following query , I used it in my code for displaying data between two dates.
SELECT * from tablename WHERE columnname BETWEEN '2014-10-20 00:00:00' AND '2014-11-25 23:59:59'
The query includes start time of the particular date to end time of ending particular date.
You edit your query according to your start and end timings.
You can use internal mysql functions for convert datetype.
I think you need DATE() and TIME() functions.
Details you can find here
Thanks for your reply guys. I have found the answer
SELECT * FROM alerts
WHERE DATE BETWEEN '2014-11-16' AND '2014-11-26'
AND TIME(DATE) BETWEEN '09:00' AND '19:00'
Is giving the expected result.. :-)

how to get the data using from date and to date in sql server?

i need to retreive data from database with the condition from date to to date using between query,
my query is,
select * from Master where Date between '01-08-2013' and '30-08-2013'
but it retreive all data from the table...
i need only data with in that date..
i tried another one like,
select * from PatientMaster where EntryDate >= '01-08-2013' and EntryDate<= '30-08-2013'
how its posible..
whats wrong with my query...
sorry im very bad in english...
thank you in advance...
A date string has the syntax YYYY-MM-DD and not DD-MM-YYYY
select * from Master
where `Date` between '2013-08-01' and '2013-08-30'
for that you can use
select * from Master where Date >='01-08-2013' and dateadd(dd,1,'30-08-2013')
You have to convert your strings to dates. This page shows you how to do it in mysql, which is what you have tagged. For sql server, which is in your subject line, use this page.
Then you do a slight modification of your 2nd attempt. Instead of
and EntryDate <= the end date
you want
and EntryDate < the day after the end date
That takes care of any time components. It might not matter in your case, but it's a good habit to get into.
You'll be looking for an query that works with your format? (dd-mm-yy)
CAST to the desired format!
http://www.w3schools.com/sql/func_convert.asp
105 = dd-mm-yy
SELECT * FROM Master
WHERE CONVERT(date, Date, 105) BETWEEN '01-08-13' and '30-08-13'
Be conscious with regards of the choice of data type for date Columns,
with or without time, day or year first etc. and please do not use varchar
for dates...
know that it CAN be confusing to call a date column for only Date...
be consistent with high/lower case.

Number of days between current date and date field

I have this problem if anyone can help.
There is a field (date) in my table (table1) that is a date in the format 3/31/1988 (M/D/y), and my necessity is to define how many days have passed since that date.
I have tried to give this instruction
SELECT DATEDIFF(CURDATE(), date) AS days
FROM table1
But it gives back 'null' and I think this happens because the two date formats are different (CURDATE() is YMD.....
Is it correct? can anyone help me?
Thank you in advance
You can use STR_TO_DATE():
SELECT DATEDIFF(CURDATE(),STR_TO_DATE(date, '%m/%d/%Y')) AS days
FROM table1
SQLFiddle Demo
Your DATE field should have DATE or DATETIME format to be used as DATEDIFF argument correctly.
Also DATE is MySQL keyword and I am not sure that you can use it as valid field name.
You can use this for accurate result
SELECT DATEDIFF(CURDATE(), DATE_FORMAT(FROM_UNIXTIME(UNIX_TIMESTAMP(`date`)), '%Y-%m-%d')) AS days FROM `table1`
If you want to consider results without - signs that you have to follow parameters position as below :
SELECT DATEDIFF(Big_Date,Small_Date) AS days FROM table1.
positive results e.g 5 (with no sign), if you place a Small date as the first parameter then it will results minus sign e.g -5.

mySQL between dates that span over multiple years

Hi I was wondering why this statement is working in mySQL
SELECT COUNT(*) AS `numrows`
FROM (`myTable`)
WHERE DATE_FORMAT(creationDateTime, '%m/%d/%Y') BETWEEN '02/21/2011' AND '03/20/2011'
but this is not
SELECT COUNT(*) AS `numrows`
FROM (`myTable`)
WHERE DATE_FORMAT(creationDateTime, '%m/%d/%Y') BETWEEN '12/21/2010' AND '03/20/2011'
The first statement returns 'xx' count of the number of rows while the second one returns '0'
The only difference I see is that the "from" date is in 2010 and the "end" date is in 2011. To test if this was the problem I queried from '12/31/2010' and it still gave me 0 results but when I set the start date as '01/01/2011' it gave me the number of records that were created in that time span.
Is there something I am missing with regards to mySQL's BETWEEN and using dates from different years?
Thanks for the help!
Try using the date format BETWEEN '2010-12-21' AND '2011-03-20'. Also remove the DATE_FORMAT() function.
So, this:
SELECT COUNT(*) AS `numrows`
FROM `myTable`
WHERE creationDateTime BETWEEN '2010-12-21' AND '2011-03-20'
DATE_FORMAT() returns a string, not a date. By using it you're forcing a string comparison instead of a date comparison. You should omit the DATE_FORMAT and use YYYY-MM-DD date strings instead.