SQL Server date format yyyymmdd - sql-server

I have a varchar column where some values are in mm/dd/yyyy format and some are in yyyymmdd.
I want to convert all mm/dd/yyyy dates into the yyyymmdd format. What is the best way to do this? Thanks
Table is Employees and column is DOB

Assuming your "date" column is not actually a date.
Select convert(varchar(8),cast('12/24/2016' as date),112)
or
Select format(cast('12/24/2016' as date),'yyyyMMdd')
Returns
20161224

DECLARE #v DATE= '3/15/2013'
SELECT CONVERT(VARCHAR(10), #v, 112)
you can convert any date format or date time format to YYYYMMDD with no delimiters

You can do as follows:
Select Format(test.Time, 'yyyyMMdd')
From TableTest test

try this....
SELECT FORMAT(CAST(DOB AS DATE),'yyyyMMdd') FROM Employees;

Select CONVERT(VARCHAR(8), GETDATE(), 112)
Tested in SQL Server 2012
https://www.w3schools.com/sql/func_sqlserver_convert.asp

In SQL Server, you can do:
select coalesce(format(try_convert(date, col, 112), 'yyyyMMdd'), col)
This attempts the conversion, keeping the previous value if available.
Note: I hope you learned a lesson about storing dates as dates and not strings.

SELECT YEAR(getdate()) * 10000 + MONTH(getdate()) * 100 + DAY(getdate())

mm/dd/yyyy corresponds to U.S. standard so if you convert to date using 101 value and then to varchar using 112 for ISO date get the expected result.
declare #table table (date_value varchar(10))
insert into #table values ('03/30/2022'),('20220330')
select date_value
--converted to varchar
,case
--mm/dd/yyyy pattern
when patindex('[0,1][0-9]/[0-3][0-9]/[0-9][0-9][0-9][0-9]',date_value)>0 then convert(varchar(10),convert(date,date_value,101),112)
else date_value end date_value_new
--converted to date
,case
when patindex('[0,1][0-9]/[0-3][0-9]/[0-9][0-9][0-9][0-9]',date_value)>0 then convert(date,date_value,101)
else convert(date,date_value,112) end date_value_date
from #table

SELECT TO_CHAR(created_at, 'YYYY-MM-DD') FROM table;
//converts any date format to YYYY-MM-DD

Related

Short Date to Date

Good Day
I am trying to convert a short date i.e 780506 to a date i.e 1978/05/06 , I have tried CASTING the date CAST(CONVERT(VARCHAR, 78) + '-' + CONVERT(VARCHAR, 05) + '-' + CONVERT(VARCHAR, 06)
AS DATETIME) but this is not working. I tried Converting the date:CONVERT(VARCHAR(6), 780506), 12) and also not working. Is there am easy way to do this? The reason I need this is that the first 6 digits of out countries ID number = Date of Birth, I am just trying to convert it into a workable date.
Thanks
Convert to date type:
DECLARE #s VARCHAR(10) = '780506'
SELECT convert(DATE, #s)
For the column:
SELECT CONVERT(DATE, ColumnName) FROM TableName
You can use CAST or CONVERT. Like this:
DECLARE #shortdate VARCHAR(10) = '780506'
SELECT CONVERT(DATE, #shortdate)
SELECT CAST(#shortdate AS DATE)
Result:
1978-05-06

Convert a SQl DateTime field with hh mm ss

I am inserting a datetime field into my SQL database with a format of 2014-10-29 12:05:24.927
My interface needs to display this as 29/10/2014 12:05:24
my tsql statement is :
SELECT Convert(VARCHAR(20), MessageAudit.AuditDate, 120) As AuditDate FROM tableA
Which, produces yyyy-MM-dd hh:mm:ss how, can i format the date portion of this to be dd/MM/yyyy?
You can use something like:
declare #Date datetime
select #Date = cast('20141029 12:05:24.927' as datetime)
select convert(nvarchar(10), #Date, 103) + ' ' + convert(nvarchar(10), #Date, 108)
It will give you precisely 29/10/2014 12:05:24
Concatenate two format dd/mm/yy & hh:mm:ss
e.g
SELECT CONVERT(NVARCHAR(10), GETDATE(), 103) + ' ' +
CONVERT(NVARCHAR(10), GETDATE(), 108) AS [Date]
Here's a pretty extensive list of date formats in sql server:
http://www.sql-server-helper.com/tips/date-formats.aspx
for your specific problem you could do:
SELECT CONVERT(VARCHAR(20), AuditDate, 103) + ' ' +
CONVERT(VARCHAR(20), AuditDate, 108) AS AuditDate
FROM tableA
Though this will return the date as a string/varchar - which has it's own set of issues. You're really better off keeping the date in a date format and formatting it on the front end. This will allow you (depending on how the date is displayed) to still be "date" sortable rather than string sortable.
As http://msdn.microsoft.com/it-it/library/ms187928.aspx, you have to specify 103 as the third parameter of the CONVERT() function.
SELECT Convert(VARCHAR(20), MessageAudit.AuditDate, 103) As AuditDate FROM tableA

How I can compare datetime datatype with string?

I would like to compare datetime datatype, like "20/12/2011 00:00:00", with compound string date format (I mean that it is composed of string of date, string of month and string of year).
For example, coloumn entime is datatime datatype which is stored "20/12/2011 00:00:00" data and other three column(date,month,year respectively) are string. so I want to compare between entime column with the date,month and year composed together, How I can write SQL Command to suppurt the above requirement ?
Hope you can help me ?
The best option is to convert the datetime to string and then make the needed comparisons.
You can see here how to make the conversion.
There is also the DATEPART function as an alternative.
SELECT *
FROM DateTable
WHERE
DATEPART(YEAR, [DATECOLUMN]) = #YearString
AND DATEPART(MONTH, [DATECOLUMN]) = #MonthString
AND DATEPART(DAY, [DATECOLUMN]) = #DayString
You can go below way, would you please try it out, thanks
SET DATEFORMAT DMY
SELECT CAST(CONVERT(VARCHAR(15), GETDATE(), 105) AS DATETIME)
SELECT CAST(('20'+'-'+'12'+'-'+'2011') AS DATETIME)
As an example:
SET DATEFORMAT DMY
SELECT CAST(CONVERT(VARCHAR(15), yourDateColumn, 105) AS DATETIME) FROM TableName
SELECT CAST((dayColumn+'-'+monthColumn+'-'+yearColumn) AS DATETIME)
FROM anotherTable
Finally the comparison:
SELECT t1.* FROM tableName t1, anotherTable t2
WHERE CAST(CONVERT(VARCHAR(15), t1.DateColumnName, 105) AS DATETIME)
= CAST((t2.dayColumn+'-'+t2.monthColumn+'-'+t2.yearColumn) AS DATETIME)
Is this your requirement ?
DECLARE #tblTemp TABLE
(
DAY VARCHAR(10)
,Month VARCHAR(10)
,Year VARCHAR(10)
)
DECLARE #dtDateTime VARCHAR(10) = '20/12/2011 00:00:00'
INSERT INTO #tblTemp VALUES
('01','01','2011'),
('01','02','2011'),
('01','03','2011'),
('01','04','2012');
select * from #tblTemp where CONVERT(DATE,Year +Month+DAY ,103) < CONVERT(DATE,#dtDateTime,103)

How to get a date in YYYY-MM-DD format from a TSQL datetime field?

How do I retrieve a date from SQL Server in YYYY-MM-DD format? I need this to work with SQL Server 2000 and up. Is there a simple way to perform this in SQL Server or would it be easier to convert it programmatically after I retrieve the result set?
I've read the CAST and CONVERT on Microsoft Technet, but the format I want isn't listed and changing the date format isn't an option.
SELECT CONVERT(char(10), GetDate(),126)
Limiting the size of the varchar chops of the hour portion that you don't want.
SELECT convert(varchar, getdate(), 100) -- mon dd yyyy hh:mmAM
SELECT convert(varchar, getdate(), 101) -- mm/dd/yyyy – 10/02/2008
SELECT convert(varchar, getdate(), 102) -- yyyy.mm.dd – 2008.10.02
SELECT convert(varchar, getdate(), 103) -- dd/mm/yyyy
SELECT convert(varchar, getdate(), 104) -- dd.mm.yyyy
SELECT convert(varchar, getdate(), 105) -- dd-mm-yyyy
SELECT convert(varchar, getdate(), 106) -- dd mon yyyy
SELECT convert(varchar, getdate(), 107) -- mon dd, yyyy
SELECT convert(varchar, getdate(), 108) -- hh:mm:ss
SELECT convert(varchar, getdate(), 109) -- mon dd yyyy hh:mm:ss:mmmAM (or PM)
SELECT convert(varchar, getdate(), 110) -- mm-dd-yyyy
SELECT convert(varchar, getdate(), 111) -- yyyy/mm/dd
SELECT convert(varchar, getdate(), 112) -- yyyymmdd
SELECT convert(varchar, getdate(), 113) -- dd mon yyyy hh:mm:ss:mmm
SELECT convert(varchar, getdate(), 114) -- hh:mm:ss:mmm(24h)
SELECT convert(varchar, getdate(), 120) -- yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) -- yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) -- yyyy-mm-ddThh:mm:ss.mmm
Starting with SQL Server 2012 (original question is for 2000):
SELECT FORMAT(GetDate(), 'yyyy-MM-dd')
The form you are after is listed in the books online documentation.
http://msdn.microsoft.com/en-us/library/aa226054(SQL.80).aspx
For example, try the following:
select convert(varchar,getDate(),120)
select convert(varchar(10),getDate(),120)
The convert function with the format specifier 120 will give you the format "yyyy-MM-dd HH:mm:ss", so you just have to limit the length to 10 to get only the date part:
convert(varchar(10), theDate, 120)
However, formatting dates is generally better to do in the presentation layer rather than in the database or business layer. If you return the date formatted from the database, then the client code has to parse it to a date again if it needs to do any calculations on it.
Example in C#:
theDate.ToString("yyyy-MM-dd")
For YYYYMMDD try
select convert(varchar,getDate(),112)
I have only tested on SQLServer2008.
I'm not sure why the simplest way has been ignored/omitted in the answers above:
SELECT FORMAT(GetDate(),'yyyy-MM-dd');--= 2020-01-02
SELECT FORMAT(GetDate(),'dd MMM yyyy HH:mm:ss');-- = 02 Jan 2020 08:08:08
I prefer the second one because whichever language you speak, you will understand what date it is!
Also SQL Server always 'understands' it when you send that to your save procedure, regardless of which regional formats are set in the computers - I always use full year (yyyy), month name (MMM) and 24 hour format (capital HH) for hour in my programming.
One other way...
CONVERT(varchar, DATEPART(yyyy, #datetime)) + '/' + CONVERT(varchar, DATEPART(mm, #datetime)) + '/' + CONVERT(varchar, DATEPART(dd, #datetime))
For those who would want the time part as well (I did), the following snippet may help
SELECT convert(varchar, getdate(), 120) -- yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) -- yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) -- yyyy-mm-ddThh:mm:ss.mmm
--example -- 2008-10-02T10:52:47.513
replace(convert(varchar, getdate(), 111), '/','-')
Will also do trick without "chopping anything off".
In case someone wants to do it the other way around and finds this.
select convert(datetime, '12.09.2014', 104)
This converts a string in the German date format to a datetime object.
Why 104? See here: http://msdn.microsoft.com/en-us/library/ms187928.aspx
In your cast and convert link, use style 126 thus:
CONVERT (varchar(10), DTvalue, 126)
This truncates the time. Your requirement to have it in yyyy-mm-dd means it must be a string datatype and datetime.
Frankly though, I'd do it on the client unless you have good reasons not to.
You may also use. This is by using the new datatype DATE. May not work in all previous versions, but greatly simplified to use in later version.
SELECT CAST(getdate() AS DATE)
SELECT LEFT(CAST(getdate() AS DATE), 7)
If you want to use it as a date instead of a varchar again afterwards, don't forget to convert it back:
select convert(datetime,CONVERT(char(10), GetDate(),126))
From SQL Server 2008 you can do this: CONVERT(date,getdate())
SELECT CONVERT(NVARCHAR(20), GETDATE(), 23)
I would use:
CONVERT(char(10),GETDATE(),126)
SELECT Code,Description FROM TABLE
-- This will Include only date part of 14th March 2010. Any date with date companents will not be considered.
WHERE ID= 1 AND FromDate >= CONVERT(DATETIME, '2010-02-14', 126) AND ToDate <= DATEADD(dd, 1, CONVERT(DATETIME, '2010-03-14', 126))
-- This will Include the whole day of 14th March 2010
--WHERE ID= 1 AND FromDate >= CONVERT(DATETIME, '2010-02-14', 126) AND ToDate < DATEADD(dd, 1, CONVERT(DATETIME, '2010-03-14', 126))
Using a CASE statement for each of the convert / cast functions always works for me:
Please replace tableXXXXY with your table name, and issueDate_dat with the name of your datetime field in that table:
SELECT issueDate_dat, CONVERT(varchar, DATEPART(yyyy, issuedate_dat)) AS issueDateYYYY
, CASE WHEN (len(CONVERT(varchar, DATEPART(mm, issuedate_dat))) < 2) THEN '0' +CONVERT(varchar, DATEPART(mm, issuedate_dat)) ELSE CONVERT(varchar, DATEPART(mm, issuedate_dat)) END AS issueDateMM
, CASE WHEN (len(CONVERT(varchar, DATEPART(dd, issuedate_dat))) <2) THEN '0' +CONVERT(varchar, DATEPART(dd, issuedate_dat)) ELSE CONVERT(varchar, DATEPART(dd, issuedate_dat)) END AS issueDateDD
FROM tableXXXXY
Hope this was helpful. chagbert.
This solution works for me, simple and effective (with 126 too)
CONVERT(NVARCHAR(MAX), CAST(GETDATE() as date), 120)
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
cmdGetPaymentStatement.Parameters.AddWithValue("#pStartDate", DateTime.Parse("22/12/2017", culture, System.Globalization.DateTimeStyles.AssumeLocal)).IsNullable = true;
Seems unnecessary to do any strange things, if you want your date to be seperated by slash.
Just escape it with a backslash. Otherwise you will end up with a dot.
SELECT FORMAT(GETDATE(),'yyyy\/MM');
Tested on SQL Server 2016
If your source date format is all messed up, try something along the lines of:
select
convert(nvarchar(50),year(a.messedupDate))+'-'+
(case when len(convert(nvarchar(50),month(a.messedupDate)))=1
then '0'+ convert(nvarchar(50),month(a.messedupDate))+'-'
else convert(nvarchar(50),month(a.messedupDate)) end)+
(case when len(convert(nvarchar(50),day(a.messedupDate)))=1
then '0'+ convert(nvarchar(50),day(a.messedupDate))+'-'
else convert(nvarchar(50),day(a.messedupDate)) end)
from messytable a
As string processing is expensive, and FORMAT more so, I am surprised that Asher/Aaron Dietz response is not higher, if not top; the question is seeking ISO 8601 date, and isn't specifically requesting it as a string type.
The most efficient method would be any of these (I've included the answer Asher/Aaron Dietz have already suggested for completeness):
All versions
select cast(getdate() as date)
select convert(date, getdate())
2008 and higher
select convert(date, current_timestamp)
ANSI SQL equivalent 2008 and higher
select cast(current_timestamp as date)
References:
https://sqlperformance.com/2015/06/t-sql-queries/format-is-nice-and-all-but
https://en.wikipedia.org/wiki/ISO_8601
https://www.w3schools.com/sql/func_sqlserver_current_timestamp.asp
https://learn.microsoft.com/en-us/sql/t-sql/functions/current-timestamp-transact-sql?view=sql-server-ver15
change GetDate() to any format as String:
SELECT FORMAT(GetDate(), 'yyyy-MM-dd HH:mm:ss')

Compare a date string to datetime in SQL Server?

In SQL Server I have a DATETIME column which includes a time element.
Example:
'14 AUG 2008 14:23:019'
What is the best method to only select the records for a particular day, ignoring the time part?
Example: (Not safe, as it does not match the time part and returns no rows)
DECLARE #p_date DATETIME
SET #p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )
SELECT *
FROM table1
WHERE column_datetime = #p_date
Note: Given this site is also about jotting down notes and techniques you pick up and then forget, I'm going to post my own answer to this question as DATETIME stuff in MSSQL is probably the topic I lookup most in SQLBOL.
Update Clarified example to be more specific.
Edit Sorry, But I've had to down-mod WRONG answers (answers that return wrong results).
#Jorrit: WHERE (date>'20080813' AND date<'20080815') will return the 13th and the 14th.
#wearejimbo: Close, but no cigar! badge awarded to you. You missed out records written at 14/08/2008 23:59:001 to 23:59:999 (i.e. Less than 1 second before midnight.)
Technique 1:
DECLARE #p_date DATETIME
SET #p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )
SELECT *
FROM table1
WHERE column_datetime >= #p_date
AND column_datetime < DATEADD(d, 1, #p_date)
The advantage of this is that it will use any index on 'column_datetime' if it exists.
In SQL Server 2008, you could use the new DATE datatype
DECLARE #pDate DATE='2008-08-14'
SELECT colA, colB
FROM table1
WHERE convert(date, colDateTime) = #pDate
#Guy. I think you will find that this solution scales just fine. Have a look at the query execution plan of your original query.
And for mine:
Just compare the year, month and day values.
Declare #DateToSearch DateTime
Set #DateToSearch = '14 AUG 2008'
SELECT *
FROM table1
WHERE Year(column_datetime) = Year(#DateToSearch)
AND Month(column_datetime) = Month(#DateToSearch)
AND Day(column_datetime) = Day(#DateToSearch)
Something like this?
SELECT *
FROM table1
WHERE convert(varchar, column_datetime, 111) = '2008/08/14'
Technique 2:
DECLARE #p_date DATETIME
SET #p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )
SELECT *
FROM table1
WHERE DATEDIFF( d, column_datetime, #p_date ) = 0
If the column_datetime field is not indexed, and is unlikely to be (or the index is unlikely to be used) then using DATEDIFF() is shorter.
Good point about the index in the answer you accepted.
Still, if you really search only on specific DATE or DATE ranges often, then the best solution I found is to add another persisted computed column to your table which would only contain the DATE, and add index on this column:
ALTER TABLE "table1"
ADD "column_date" AS CONVERT(DATE, "column_datetime") PERSISTED
Add index on that column:
CREATE NONCLUSTERED INDEX "table1_column_date_nu_nci"
ON "table1" ( "column_date" ASC )
GO
Then your search will be even faster:
DECLARE #p_date DATE
SET #p_date = CONVERT( DATE, '14 AUG 2008', 106 )
SELECT *
FROM table1
WHERE column_date = #p_date
I normally convert date-time to date and compare them, like these:
SELECT 'Same Date' WHERE CAST(getDate() as date) = cast('2/24/2012 2:23 PM' as date)
or
SELECT 'Same Date' WHERE DATEDIFF(dd, cast(getDate() as date), cast('2/24/2012 2:23 PM' as date)) = 0
This function Cast(Floor(Cast(GetDate() As Float)) As DateTime) returns a datetime datatype with the time portion removed and could be used as so.
Select
*
Table1
Where
Cast(Floor(Cast(Column_DateTime As Float)) As DateTime) = '14-AUG-2008'
or
DECLARE #p_date DATETIME
SET #p_date = Cast('14 AUG 2008' as DateTime)
SELECT *
FROM table1
WHERE Cast(Floor(Cast(column_datetime As Float)) As DateTime) = #p_date
How to get the DATE portion of a DATETIME field in MS SQL Server:
One of the quickest and neatest ways to do this is using
DATEADD(dd, DATEDIFF( dd, 0, #DAY ), 0)
It avoids the CPU busting "convert the date into a string without the time and then converting it back again" logic.
It also does not expose the internal implementation that the "time portion is expressed as a fraction" of the date.
Get the date of the first day of the month
DATEADD(dd, DATEDIFF( dd, -1, GetDate() - DAY(GetDate()) ), 0)
Get the date rfom 1 year ago
DATEADD(m,-12,DATEADD(dd, DATEDIFF( dd, -1, GetDate() - DAY(GetDate()) ), 0))
I know this isn't exactly how you want to do this, but it could be a start:
SELECT *
FROM (SELECT *, DATEPART(yy, column_dateTime) as Year,
DATEPART(mm, column_dateTime) as Month,
DATEPART(dd, column_dateTime) as Day
FROM table1)
WHERE Year = '2008'
AND Month = '8'
AND Day = '14'
SELECT *
FROM table1
WHERE CONVERT(varchar(10),columnDatetime,121) =
CONVERT(varchar(10),CONVERT('14 AUG 2008' ,smalldatetime),121)
This will convert the datatime and the string into varchars of the format "YYYY-MM-DD".
This is very ugly, but should work
Date can be compared in sqlserver using string comparision:
e.g.
DECLARE #strDate VARCHAR(15)
SET #strDate ='07-12-2010'
SELECT * FROM table
WHERE CONVERT(VARCHAR(15),dtInvoice, 112)>= CONVERT(VARCHAR(15),#strDate , 112)
DECLARE #Dat
SELECT *
FROM Jai
WHERE
CONVERT(VARCHAR(2),DATEPART("dd",Date)) +'/'+
CONVERT(VARCHAR(2),DATEPART("mm",Date)) +'/'+
CONVERT(VARCHAR(4), DATEPART("yy",Date)) = #Dat
The best way is to simply extract the date part using the SQL DATE() Function:
SELECT *
FROM table1
WHERE DATE(column_datetime) = #p_date;
SELECT * FROM tablename
WHERE CAST(FLOOR(CAST(column_datetime AS FLOAT))AS DATETIME) = '30 jan 2012'
SELECT CONVERT(VARCHAR(2),DATEPART("dd",doj)) +
'/' + CONVERT(VARCHAR(2),DATEPART("mm",doj)) +
'/' + CONVERT(VARCHAR(4),DATEPART("yy",doj)) FROM emp
There are many formats for date in SQL which are being specified. Refer https://msdn.microsoft.com/en-in/library/ms187928.aspx
Converting and comparing varchar column with selected dates.
Syntax:
SELECT * FROM tablename where CONVERT(datetime,columnname,103)
between '2016-03-01' and '2016-03-03'
In CONVERT(DATETIME,COLUMNNAME,103) "103" SPECIFIES THE DATE FORMAT as dd/mm/yyyy
In sqlserver
DECLARE #p_date DATE
SELECT *
FROM table1
WHERE column_dateTime=#p_date
In C#
Pass the short string of date value using ToShortDateString() function.
sample:
DateVariable.ToShortDateString();

Resources