SQL - Convert varchar (dd/mm/yyyy hh.mm AM/PM) to datetime - sql-server

I'm trying to convert a varchar field to datetime. The data in the varchar field looks like this dd/mm/yyyy hh.mm AM/PM.
I'm actually trying to extract the date part & time part and convert them to date and time respectively.
And I use the below query to extract the date part from the varchar and convert it to date.
SELECT DISTINCT LEFT([Start Date], 10)
,CASE WHEN ISDATE(LEFT([Start Date], 10)) = 1
THEN CONVERT(DATETIME, LEFT([Start Date], 10), 120)
END
,ISDATE(LEFT([Start Date], 10))
FROM [dbo].[TestTable]
I have timestamp in the format mentioned above for entire August.
But the query gives me the result in yyyy-dd-mm format and the date are converted to date format only till 12 Aug'15. Date after 12 of Aug is null. I know it's because, in the case statement they are returned 0. How can I convert those values also to date?
Any suggestions to convert all the values to yyyy-mm-dd hh:mm:ss will be very helpful.
Thanks in advance.

You could use SET DATEFORMAT as lad2025 suggested.
SET DATEFORMAT dmy
Or you can use the following in your CONVERT()
DECLARE #date VARCHAR(16) = '13/08/2015 11:13';
SELECT CONVERT(DATETIME, #date, 103)
103 is the code for dd/mm/yyyy.

Related

How to handle MMddyyyy date format in SQL Server?

I am getting the date in following string formats from third party vendor API:
MM/dd/yyyy
yyyy/MM/dd
yyyyMMdd
yyyy-MM-dd
MMddyyyy
So some of the records have date of birth in yyyy-MM-dd and some of the records have DOB in other format.
Except format MMddyyyy, all the formats are converted to yyyy-MM-dd using SQL Convert/Cast function.
How do I convert MMddyyyy it to yyyy-MM-dd?
I am trying below statement in SQL Server 2019 but its not working:
DECLARE #dt varchar(8)= '02022020';
SELECT CAST(#dt as date) s1;
Msg 241, Level 16, State 1, Line 20
Conversion failed when converting date and/or time from character string.
Is there any way I can handle this scenario in SQL Server?
Be informed: I am trying to implement below ADF code using SQL stored procedure.
coalesce(toDate(DOB,'MM/dd/yyyy')
,toDate(DOB,'yyyy/MM/dd')
,toDate(DOB,'yyyyMMdd')
,toDate(DOB,'MMddyyyy')
,toDate(DOB,'yyyy-MM-dd'))
There is no style code for MMddyyyy as far as I am aware, so the easiest way is probably to just convert the string to yyyyMMdd first, e.g.
CONCAT(RIGHT(#dt, 4), LEFT(#dt, 4))
Then convert that to a date:
DECLARE #dt varchar(8)= '02022020';
SELECT CONVERT(DATE, CONCAT(RIGHT(#dt, 4), LEFT(#dt, 4)), 112)
Below is the SQL statements to handle all the formats.
MM/dd/yyyy
yyyy/MM/dd
yyyyMMdd
yyyy-MM-dd
MMddyyyy
DECLARE #date varchar(10)= '2020-03-15';
SELECT CASE
WHEN #date IS NULL
THEN NULL
WHEN TRY_CONVERT(DATE, #date) IS NOT NULL
THEN CAST(#date AS DATE)
WHEN TRY_CONVERT(DATE, #date) IS NULL
THEN CONVERT(DATE, CONCAT(RIGHT(#date, 4), LEFT(#date, 4)), 112)
END;
Have you tried the following? SELECT FORMAT (yourdate, 'MM-dd-yy'). let me know

How to convert from DD/mm/yyyy in varchar(max) to yyyymmdd format in SQL Server

Dates in DD/mm/yyyy format stored in a varchar(max) column need to be converted to yyyymmdd format.
The below options to convert / cast are not supported.
CONVERT(VARCHAR(19), CONVERT(DATETIME, wfm.date, 3), 112)
CONVERT(VARCHAR(50), CAST(wfm.date AS DATETIME2), 112)
CAST(CAST(wfm.date AS DATETIME2(15)) AS DATETIME)
I'm getting an error message for CONVERT syntax:
Conversion failed when converting date and/or time from character string.
For CAST syntax, I'm getting this error:
Line 1: Specified scale 15 is invalid. 'dd/mm/yyyy/ in varchar to be converted to yyyymmdd format
Ideally, don't store dates as a varchar, store them as a date and worry about the format they are displayed in in your presentation layer. Therefore, you should just do:
SELECT TRY_CONVERT(date,YourVarcharMAXDate,103);
If you must get the format yyyyMM`` (i don't recommend, change your data type of your column todate), then you can use a furterhCONVERT`:
SELECT CONVERT(varchar(8),TRY_CONVERT(date,YourVarcharMAXDate,103),112);
If the data engine can't convert the date, due to it being an invalid format, TRY_CONVERT will return NULL; you'll need to fix those values (make them valid). Another good reason why not to use a varchar to store a date.
Maybe this helps
DECLARE #dt DATETIME= '2019-12-31 14:43:35.863';
SELECT CONVERT(VARCHAR(10), #dt, 11) s1,
CONVERT(VARCHAR(10), #dt, 111) s2;
You could always just use substring for this. Example is shown below.
DECLARE #samples TABLE
(
Dates NVARCHAR(50)
)
INSERT INTO #samples VALUES
('10/11/2018'),
('12/11/2018'),
('15/11/2018'),
('17/11/2018'),
('19/11/2018'),
('20/11/2018')
SELECT
SUBSTRING(Dates, 7,4) +
SUBSTRING(Dates, 4,2) +
SUBSTRING(Dates, 1,2) as [NewDate]
FROM #samples
Output will be a list of strings with your required format. This won't validate for you, but you can always try convert these to a date using CAST and it should correctly cast the yyyyMMdd to a date if the date is correct.
If you're using SQL Server 2016 or newer, you can use PARSE and FORMAT to do this quite easily:
SELECT
FORMAT(PARSE(wfm.Date AS DATE USING 'de-DE'), 'yyyyMMdd')
FROM
dbo.WhateverYourTableNameIS
The dd/mm/yyyy format is the format used e.g. in Germany, that's why I'm using the de-DE culture to convert that string to a DATE. Then you can format it using the usual formatting strings as used in C#/.NET.
select convert(varchar, convert(datetime, wfm.date, 103), 112)

CAST () OR CONVERT () not changing date-time format to string in SQL Server 2008

I have a column which is of datetime type.
I want to separate date and time for which i used left() & right() enclosed by cast() or convert() like below :
Select BATCH,
LEFT( CAST(S_DATE AS VARCHAR(20)),12) AS ST_DATE,
RIGHT( CAST(S_DATE AS VARCHAR(20)),8) AS ST_TIME,
LEFT( CAST(E_DATE AS VARCHAR(20)),12) AS E_DATE,
RIGHT( CAST(E_DATE AS VARCHAR(20)),8) AS E_TIME
INTO CRYST2
From Z_BATCH;
this is my actual format for datetime column :-
2015-10-01 14:00:00.000
But the problem is that it is separating the date and time accurately but it isn't returning the output in string form, as the output itself turns to date & time format respectively in their respective columns.
Following is the output I am getting:-
1 Oct 1 2015 2:00PM Oct 1 2015 2:30PM
As you can clearly see the columns I separated after date-time to string conversion is still giving me output in some date-time format only.
please help regarding it.
this is my actual format for datetime column :
2015-10-01 14:00:00.000
No, it's not. A datetime value doesn't have a format at all, it only represents a point in time. It only gets a format when you convert it to a string.
You are not specifying any format at all when you convert the datetime values, so it will be using the default format (0). You can use the format that you saw the datetime values displayed as (121) to get the desired result:
Select BATCH,
LEFT( CAST(S_DATE AS VARCHAR(19),121),10) AS ST_DATE,
RIGHT( CAST(S_DATE AS VARCHAR(19),121),8) AS ST_TIME,
LEFT( CAST(E_DATE AS VARCHAR(19),121),10) AS E_DATE,
RIGHT( CAST(E_DATE AS VARCHAR(19),121),8) AS E_TIME
INTO CRYST2
From Z_BATCH;
Cast The date and the Time in the exact format like:
CAST(S_DATE AS Time) AS ST_TIME
CAST(S_DATE AS Date) AS ST_Date
will return:
14:00:00
2015-10-01
Use CONVERT with format 120 to get the desired result, it always return the format yyyy-MM-dd hh:mm:ss
CONVERT(varchar(20), S_DATE, 120)
You can try this, if you want to get results in string format:
select convert(varchar(11),cast(S_DATE as date),106)
select convert(varchar(11),cast(S_DATE as time),100)
If you try to get answers in date and time format, try this:
CAST(S_DATE AS Time) AS ST_TIME
CAST(S_DATE AS Date) AS ST_Date

How to turn DD/MM/YYYY 00:00:0000 to MM/YYYY and keep it as date format and not string

How to turn DD/MM/YYYY 00:00:0000 to MM/YYYY and keep it as date format and not string in MS SQL
i have tried many options but still did not find the right one.
Simply you cannot keep date as mm/yyyy as a date/datetime. But you could keep it as a string and also convert when needed back to a date as below.
Sql-Server Fiddle Example
declare #dt datetime = getdate(),
#mmyyyy varchar(7)
--To format as mm/yyyy
select #mmyyyy = right(convert(varchar(10), #dt, 103),7)
--To convert back to datetime type from mm/yyyy varchar
select #mmyyyy [mm/yyyy],
convert(datetime,'01/'+ #mmyyyy,103) back_To_Date

Convert a SQL Server datetime to a shorter date format

I have a datetime column in SQL Server that gives me data like this 10/27/2010 12:57:49 pm and I want to query this column but just have SQL Server return the day month and year - eg. 2010 10 27 or something like that.
What are the functions I should be researching?
Should I be trying to convert to another date data type? Or simply convert it to a string?
Have a look at CONVERT. The 3rd parameter is the date time style you want to convert to.
e.g.
SELECT CONVERT(VARCHAR(10), GETDATE(), 103) -- dd/MM/yyyy format
Try this:
print cast(getdate() as date )
If you need the result in a date format you can use:
Select Convert(DateTime, Convert(VarChar, GetDate(), 101))
In addition to CAST and CONVERT, if you are using Sql Server 2008, you can convert to a date type (or use that type to start with), and then optionally convert again to a varchar:
declare #myDate date
set #myDate = getdate()
print cast(#myDate as varchar(10))
output:
2012-01-17
If you have a datetime field that gives the results like this 2018-03-30 08:43:28.177
Proposed: and you want to change the datetime to date to appear like 2018-03-30
cast(YourDateField as Date)
With SQL Server 2005, I would use this:
select replace(convert(char(10),getdate(),102),'.',' ')
Results: 2015 03 05
The shortest date format of mm/dd/yy can be obtained with:
Select Convert(varchar(8),getdate(),1)
Just add date keyword.
E.g. select date(orderdate),count(1) from orders where orderdate > '2014-10-01' group by date(orderdate);
orderdate is in date time.
This query will show the orders for that date rather than datetime.
Date keyword applied on a datetime column will change it to short date.
For any versions of SQL Server: dateadd(dd, datediff(dd, 0, getdate()), 0)
The original DateTime field : [_Date_Time]
The converted to Shortdate : 'Short_Date'
CONVERT(date, [_Date_Time]) AS 'Short_Date'

Resources