MySQL STR_TO_DATE() function returns null - mysql

I wanted to convert my date format From MMMM dd,yyyy to yyyy-MM-dd.
I tried using the following:
SET #dt_to = STR_TO_DATE(dateTo, '%d-%m-%Y');
but returns a NULL value.
How will I convert my date to yyyy-MM-dd format in MySQL?
EDITED:
I am creating a procedure in which the value of dateTo was received in the parameter. It is a date in MMMM dd, yyyy format. E.g. October 10, 2015.
NOTE:
The whole query does not return NULL when I use:
SET #dt_to = dateTo;

To convert the date format first you need to use STR_TO_DATE to convert the input string to a date value
SET #dt_to = STR_TO_DATE(dateTo, '%M %d,%Y');
and then convert that date value to your required format
SET #dt_converted = DATE_FORMAT(dt_to, '%Y-%m-%d');
or all in 1 go
SET #dt_to = DATE_FORMAT(STR_TO_DATE(dateTo, '%M %d,%Y'), '%Y-%m-%d');

If it's returning null then that means the extracted datetime value is illegal. You can try like below. See MySQL Documentation for more information.
SELECT STR_TO_DATE('October 10, 2015','%M %d,%Y');

Related

Convert date column in MYSQL to different format

I need to update column pubDate_Date to 2018-02-04 20:39:55 from column pubDate with format Sun, 04 Feb 2018 20:39:55 +0100.
I have tried the following, but without success:
UPDATE `feeds` SET `pubDate_Date` = date('Y-m-d H:i:s', strtotime(`pubDate`))
Hope someone can point me in the right direction
In general, you can use MySQL's STR_TO_DATE() function:
UPDATE feeds SET pubDate_Date = STR_TO_DATE(pubDate, '%a, %d %b %Y %T')
However there's no format code for timezone offsets, which MySQL will therefore ignore from the end of your original string (instead interpreting each string to be in the session's time_zone). Therefore:
If all records are in the same timezone, you could simply do SET time_zone = '+01:00' before the above update command.
Otherwise, do the following instead to adjust each time to the intended timezone:
UPDATE feeds SET pubDate_Date = CONVERT_TZ(
STR_TO_DATE(pubDate, '%a, %d %b %Y %T'),
##session.time_zone,
CONCAT(SUBSTR(pubDate, -5, 3), ':', RIGHT(pubDate, 2)
)

converting date and time without delimiter to date time with delimiter in sql server

I would like to convert date(without any delimiter ex. 31012015) and time(without any delimiter ex.0144) to date and time with delimiter. i.e.
31012015 => 31/01/2015 (dd/mm/yyyy)
0144 => 01:44 (hh:mm)
I tried various option in sql server (using various date-time format) but couldn't able to find out its solution.
try this
select replace(CONVERT(VARCHAR(10), GETDATE(), 103),'/','') as date_format,
left(replace(CONVERT(VARCHAR(10), GETDATE(), 108),':',''),4) timeformat
Since you only seem to care about the string representation of the value, you could use STUFF:
SELECT STUFF(#time, 3, 0, ':') as NewTime,
STUFF(STUFF(#date, 3, 0, '/'), 6, 0, '/') as NewDate
If you want your DATETIME without any delimiter, you can try this:
SELECT
replace(convert(varchar, getdate(),112),'/','') + replace(convert(varchar, getdate(),108),':','')

is it possible to achieve String to DateTime Conversion in sql server like mysql?

I have created store procedure in mysql for string to datetime conversion. in my application data is dynamic I mean user import CSV file so only user know data format. so user specify data format like DD/MM/YYYY or YYYY-MM-DD or anything the data contain with any separator. I parse this Date Format and convert into mysql string to date conversion format like %d/%m/%Y and use STR_TO_DATE function.
Everything works perfect.
Now I want to achieve same functionality in sql server but in sql server there are some numbers for each date format like 100 in below example.
SELECT convert(datetime, 'Oct 23 2012 11:01AM', 100) -- mon dd yyyy hh:mmAM (or PM)
so in sql server it looks like for some date formats some numbers are fixed.
In my case I want to make date format dynamic so user can enter any date format with any separator.
so anyone has any idea how to achieve same string to datetime conversion functionality in sql server same as in mysql i already have achieved and explain as above.
Thanks in advance.
The thirt parameter in the convert function is optional. If you omit it, you can use it to convert different date formats. These all give the same result (at least with my culture settings):
select convert(datetime, 'Oct 23 2012 11:01AM')
union all
select convert(datetime, '2012-10-23 11:01')
union all
select convert(datetime, '2012/10/23 11:01')
union all
select convert(datetime, '10/23/2012 11:01')
union all
select convert(datetime, '2012 Oct 23 11:01')
Note that the current culture setting will be used to determine some formats. the format 10/23/2012 is a valid date with my settings, but not 23/10/2012. The opposite may be the case with your settings.
I am sorry to say, but the convert using a numeric representing the date format is the only possibility in SQL Server next to creating an own implementation using a stored procedure.
You could optionally create a table containing the various date formats and join that with this statement to get the correct number out, but that sounds not like a real solution to me.
The only solution seems to be to accept this.
I found a sql server function that might assist you in what you want.
CREATE FUNCTION dbo.fnFormatDate (#Datetime DATETIME, #FormatMask VARCHAR(32))
RETURNS VARCHAR(32)
AS
BEGIN
DECLARE #StringDate VARCHAR(32)
SET #StringDate = #FormatMask
IF (CHARINDEX (‘YYYY’,#StringDate) > 0)
SET #StringDate = REPLACE(#StringDate, ‘YYYY’,
DATENAME(YY, #Datetime))
IF (CHARINDEX (‘YY’,#StringDate) > 0)
SET #StringDate = REPLACE(#StringDate, ‘YY’,
RIGHT(DATENAME(YY, #Datetime),2))
IF (CHARINDEX (‘Month’,#StringDate) > 0)
SET #StringDate = REPLACE(#StringDate, ‘Month’,
DATENAME(MM, #Datetime))
IF (CHARINDEX (‘MON’,#StringDate COLLATE SQL_Latin1_General_CP1_CS_AS)>0)
SET #StringDate = REPLACE(#StringDate, ‘MON’,
LEFT(UPPER(DATENAME(MM, #Datetime)),3))
IF (CHARINDEX (‘Mon’,#StringDate) > 0)
SET #StringDate = REPLACE(#StringDate, ‘Mon’,
LEFT(DATENAME(MM, #Datetime),3))
IF (CHARINDEX (‘MM’,#StringDate) > 0)
SET #StringDate = REPLACE(#StringDate, ‘MM’,
RIGHT(’0′+CONVERT(VARCHAR,DATEPART(MM, #Datetime)),2))
IF (CHARINDEX (‘M’,#StringDate) > 0)
SET #StringDate = REPLACE(#StringDate, ‘M’,
CONVERT(VARCHAR,DATEPART(MM, #Datetime)))
IF (CHARINDEX (‘DD’,#StringDate) > 0)
SET #StringDate = REPLACE(#StringDate, ‘DD’,
RIGHT(’0′+DATENAME(DD, #Datetime),2))
IF (CHARINDEX (‘D’,#StringDate) > 0)
SET #StringDate = REPLACE(#StringDate, ‘D’,
DATENAME(DD, #Datetime))
RETURN #StringDate
END
GO
The usage of the function is the following:
SELECT dbo.fnFormatDate (getdate(), ‘MM/DD/YYYY’) – 01/03/2012
SELECT dbo.fnFormatDate (getdate(), ‘DD/MM/YYYY’) – 03/01/2012
SELECT dbo.fnFormatDate (getdate(), ‘M/DD/YYYY’) – 1/03/2012
SELECT dbo.fnFormatDate (getdate(), ‘M/D/YYYY’) – 1/3/2012
SELECT dbo.fnFormatDate (getdate(), ‘M/D/YY’) – 1/3/12
SELECT dbo.fnFormatDate (getdate(), ‘MM/DD/YY’) – 01/03/12
SELECT dbo.fnFormatDate (getdate(), ‘MON DD, YYYY’) – JAN 03, 2012
SELECT dbo.fnFormatDate (getdate(), ‘Mon DD, YYYY’) – Jan 03, 2012
SELECT dbo.fnFormatDate (getdate(), ‘Month DD, YYYY’) – January 03, 2012
SELECT dbo.fnFormatDate (getdate(), ‘YYYY/MM/DD’) – 2012/01/03
SELECT dbo.fnFormatDate (getdate(), ‘YYYYMMDD’) – 20120103
SELECT dbo.fnFormatDate (getdate(), ‘YYYY-MM-DD’) – 2012-01-03
– CURRENT_TIMESTAMP returns current system date and time in standard internal format
SELECT dbo.fnFormatDate (CURRENT_TIMESTAMP,‘YY.MM.DD’) – 12.01.03
Of course you can expand the function so it also can handle times
Reference:
How to format datetime & date in Sql Server 2005
convert function in sqlserver gives you the format.
Here is same question asked : -
Sql Server string to date conversion
SQL Server convert string to datetime
You are not written your sqlserver version : if 2012 , then check link-
http://www.databasejournal.com/features/mssql/the-format-function-in-sql-server-2012.html
You can uset ISDATE function to check that string is valid datetime value.
Make a sp, not a function because it not handle try... catch.. block
create procedure dbo.strToDatefunction
(
#dateString varchar(50)
)
as
BEGIN
Declare #ConvertDateInMDYFormat datetime
set dateformat dmy
/*now start arbitraory string to convert and handle in try catch , so next format apply to convert*/
BEGIN TRY
set #ConvertDateInMDYFormat = (select #dateString,convert(varchar,#dateString,101),101,'mm/dd/yy')
END TRY
BEGIN CATCH
END CATCH
/*apply second format you want */
BEGIN TRY
set #ConvertDateInMDYFormat = (select #dateString,convert(varchar,#dateString,101),103,'mm/dd/yy')
END TRY
BEGIN CATCH
END CATCH
.... apply all format as above which possbile to give datetime as per your requirement
return #ConvertDateInMDYFormat
END

SQL Server equivalent of MySQL DATE_FORMAT()

Hope we're having a good day and all set for Christmas.
Got a quick question. I'm converting a MySQL function into SQL Server, I've got most of the function converted except for one part which has the following:
#description = CONCAT(#description, date_format(#INLastUpdated, '%H:%i %d %b %Y'))
What I'm trying to do is to basically recreate the date_format function to format the date in the same way specified, but I'm not sure how to do it. from what I've seen in the MySQL documentation the format selected would give hour:minute day / short month name / year.
Anyone got any ideas?
You can try this:
DECLARE #description VARCHAR(1000) = 'test'
DECLARE #INLastUpdated DATETIME = '2012-12-21 14:32:22'
SET #description = #description + ' '
+ LEFT(CONVERT(VARCHAR(8), #INLastUpdated, 8), 5) + ' '
+ CONVERT(VARCHAR(20), #INLastUpdated, 106)
SELECT #description
But be careful as format 106 depends on local language settings. Read more on MSDN
The equivalent function is CONVERT. But you're basically out of luck. SQL Server does not allow to cherry-pick the date tokens. You need to browse the available full date built-in formats and choose one, or try to compose an output by string concatenation, as in:
CONVERT(VARCHAR, CURRENT_TIMESTAMP, 103) + ' ' + CONVERT(VARCHAR(8), CURRENT_TIMESTAMP, 114)
Which version of SQL Server? In SQL Server 2012 we now have the FORMAT function.
This, in MySQL
date_format(#INLastUpdated, '%H:%i %d %b %Y')
translates into something like this for SQL Server 2012 using the FORMAT function:
DECLARE #d DATETIME = GETDATE();
SELECT FORMAT(#d, 'HH:mm d MMM yyyy', 'en-US') AS 'DateTime Result';
BOL SQL Server 2012 > FORMAT (Transact-SQL)

problem with convert text to time in sql server 2008?

i have this Ttime as nvarchar(10): "09:52:48" and i have TmpTime as date
and i try to convert like this: "UPDATE MEN SET TmpTime = CONVERT(DATETIME, Ttime ,108 )"
and i get in TmpTime this: "1900-01-01"
why ?
thank's in advance
If you also have a date field, you should to concatenate them before to cast:
CREATE TABLE #Sample ( DateField varchar(10), TimeField varchar(10) );
GO
INSERT INTO #Sample VALUES ('2009-01-24', '09:52:48');
SELECT CONVERT(DATETIME, DateField + ' ' + TimeField) as Converted FROM #Sample
And you'll get:
Converted
-----------------------
2009-01-24 09:52:48.000
You have a column defined as "date" and then you are sending only a time value into it
The date portion defaults to zero which is 01 January 1900 in SQL (in the CONVERT). Then the time is ignored for a date column.
What do you expect to happen?
(The same would happen whether or not you use CONVERT or not because the column is "date")