SQL Server : convert date to YYYMMDD? - sql-server

I have a date in one of the column in SQL Server, the sample dates are:
10/02/2012
23/11/2012
13/01/2012
10/02/2012
10/02/2012
I have tried the approach to convert the dates to YYYYMMDD
DECLARE #v DATE= '1/11/2012'
SELECT CONVERT(VARCHAR(10), #v, 112)
I have another column in a same table in which i want to update the date in YYYYMMDD format ,the problem here is that the date are not proper
and throws an error
DECLARE #v DATE= '23/11/2012'
SELECT CONVERT(VARCHAR(10), #v, 112)
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
Any help is appreciated in this, The date will come in any order either dd/mm/yyyy or mm/dd/yyyy, it should be able to convert it properly

You may try using the following format to one data type to another.(dd/mm/yyyy to yyyy/mm/dd)
CONVERT(data_type(length),expression,style)
As well as update like following
UPDATE table_name SET
destination_column_name=orig_column_name
WHERE condition_if_necessary

if you want to insert date in SQL server you want to follow certain formats. You can follow either yyyy-MM-dd or MM-dd-yyyy
for your question if you follow MM-dd-yyyy this format and if you using SQL server 2012 or newer you can use this and you can get the result
DECLARE #v DATE = '11/23/2012';
SELECT FORMAT ( #v, 'yyyy/MM/dd', 'en-US' )
Refer these links FORMAT (Transact-SQL) , SQL Server date format function

Related

String with dd-MM-yyyy hh:mm:ss format to datetime in SQL Server

I'm trying to convert a nvarchar(max) column to a datetime in SQL Server. The format is dd-MM-yyyy hh:mm:ss, which I'd like to keep, however I'd like to change the type to datetime. I've found many similar questions about this conversion, but not with my particular format.
I've tried CONVERT(nvarchar(MAX), string_column, 121), however without luck. How can this be done? As example, I'd like to convert the string 26-11-2021 08:19:16 to datetime.
This works for me:
SELECT CONVERT(datetime2(0), '26-11-2021 08:19:16', 105);
/* Output: 2021-11-26 08:19:16 */
Recent versions of SQL Server also have the TRY_PARSE method:
SELECT TRY_PARSE('26-11-2021 08:19:16' As datetime2(0) USING 'en-GB')
/* Output: 2021-11-26 08:19:16 */
DECLARE #InString NVARCHAR(20)='26-11-2021 08:19:16';
SELECT #InString;
SELECT CONVERT(DATETIME,#InString,105);
Could you please try if it is suitable for you

How to convert it to a date format in SQL Server

I am trying to convert this time 2021-08-16 12:58:00.000 to a DateTime this way:
SELECT Convert(datetime, '16/08/2021 12:58:00:000PM');
And getting "Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.".
What am I doing wrong? Is it an invalid date time?
The issue is that your date is formatted at dd/mm/yyyy and SQL Server expects it as mm/dd/yyyy. In fact, if you do this it will succeed:
SELECT CONVERT(datetime, '08/16/2021 12:58:00:000PM');
To make it work for your format, you need to pass a style value to let SQL Server know the format you are using. For your example, this works:
SELECT CONVERT(datetime, '16/08/2021 12:58:00:000PM', 103);
103 corresponds to dd/mm/yyyy. You can see a full list of style values in the documentation at https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15

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)

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

How to convert a datetime to string in T-SQL

I'm surprised not to be able to find this question here already.
I have a date time var and I want to convert it to a string so that I can append it to another string. I want it in a format that can be converted easily back to a date time.
How can I do this?
(I want the date part and the time part.)
The following query will get the current datetime and convert into string. with the following format yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar(25), getdate(), 120)
SQLFiddle Demo
SQL Server Date Formats
There are many different ways to convert a datetime to a string. Here is one way:
SELECT convert(varchar(25), getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm
See Demo
Here is a website that has a list of all of the conversions:
How to Format datetime & date in SQL Server
In addition to the CAST and CONVERT functions in the previous answers, if you are using SQL Server 2012 and above you use the FORMAT function to convert a DATETIME based type to a string.
To convert back, use the opposite PARSE or TRYPARSE functions.
The formatting styles are based on .NET (similar to the string formatting options of the ToString() method) and has the advantage of being culture aware. eg.
DECLARE #DateTime DATETIME2 = SYSDATETIME();
DECLARE #StringResult1 NVARCHAR(100) = FORMAT(#DateTime, 'g') --without culture
DECLARE #StringResult2 NVARCHAR(100) = FORMAT(#DateTime, 'g', 'en-gb')
SELECT #DateTime
SELECT #StringResult1, #StringResult2
SELECT PARSE(#StringResult1 AS DATETIME2)
SELECT PARSE(#StringResult2 AS DATETIME2 USING 'en-gb')
Results:
2015-06-17 06:20:09.1320951
6/17/2015 6:20 AM
17/06/2015 06:20
2015-06-17 06:20:00.0000000
2015-06-17 06:20:00.0000000
SELECT CONVERT(varchar, #datetime, 103) --for UK Date format 'DD/MM/YYYY'
101 - US - MM/DD/YYYY
108 - Time - HH:MI:SS
112 - Date - YYYYMMDD
121 - ODBC - YYYY-MM-DD HH:MI:SS.FFF
20 - ODBC - YYYY-MM-DD HH:MI:SS
There are 3 different methods depending on what I is my requirement and which version I am using.
Here are the methods..
1) Using Convert
DECLARE #DateTime DATETIME = GETDATE();
--Using Convert
SELECT
CONVERT(NVARCHAR, #DateTime,120) AS 'myDateTime'
,CONVERT(NVARCHAR(10), #DateTime, 120) AS 'myDate'
,RIGHT(CONVERT(NVARCHAR, #DateTime, 120),8) AS 'myTime'
2) Using Cast (SQL Server 2008 and beyond)
SELECT
CAST(#DateTime AS DATETIME2) AS 'myDateTime'
,CAST(#DateTime AS DATETIME2(3)) AS 'myDateTimeWithPrecision'
,CAST(#DateTime AS DATE) AS 'myDate'
,CAST(#DateTime AS TIME) AS 'myTime'
,CAST(#DateTime AS TIME(3)) AS 'myTimeWithPrecision'
3) Using Fixed-length character data type
DECLARE #myDateTime NVARCHAR(20) = CONVERT(NVARCHAR, #DateTime, 120);
DECLARE #myDate NVARCHAR(10) = CONVERT(NVARCHAR, #DateTime, 120);
SELECT
#myDateTime AS 'myDateTime'
,#myDate AS 'myDate'
You can use the convert statement in Microsoft SQL Server to convert a date to a string. An example of the syntax used would be:
SELECT convert(varchar(20), getdate(), 120)
The above would return the current date and time in a string with the format of YYYY-MM-DD HH:MM:SS in 24 hour clock.
You can change the number at the end of the statement to one of many which will change the returned strings format. A list of these codes can be found on the MSDN in the CAST and CONVERT reference section.
Check CAST and CONVERT syntax of t-sql:
http://msdn.microsoft.com/en-us/library/ms187928.aspx
Try below :
DECLARE #myDateTime DATETIME
SET #myDateTime = '2013-02-02'
-- Convert to string now
SELECT LEFT(CONVERT(VARCHAR, #myDateTime, 120), 10)
This has been answered by a lot of people, but I feel like the simplest solution has been left out.
SQL SERVER (I believe its 2012+) has implicit string equivalents for DATETIME2 as shown here
Look at the section on "Supported string literal formats for datetime2"
To answer the OPs question explicitly:
DECLARE #myVar NCHAR(32)
DECLARE #myDt DATETIME2
SELECT #myVar = #GETDATE()
SELECT #myDt = #myVar
PRINT(#myVar)
PRINT(#myDt)
output:
Jan 23 2019 12:24PM
2019-01-23 12:24:00.0000000
Note:
The first variable (myVar) is actually holding the value '2019-01-23 12:24:00.0000000' as well. It just gets formatted to Jan 23 2019 12:24PM due to default formatting set for SQL SERVER that gets called on when you use PRINT. Don't get tripped up here by that, the actual string in (myVer) = '2019-01-23 12:24:00.0000000'
In the stored procedure for me works something like this.
convert(varchar(10), StartingDate) AS 'StartingDate'

Resources