Conversion issues with VARCHAR to DATE - sql

I have sample data like this :
SELECT CONVERT(CHAR(19), CONVERT(DATE, '11/10/1997', 3), 120);
when i execute this I'm getting Error like this :
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character
string.
So then i have removed first 2 characters of year 1997
SELECT CONVERT(CHAR(19), CONVERT(DATE, '11/10/97', 3), 120);
And it gave Result Set like this :
Date
1997-10-11
So it got converted from DD/MM/YY Format to YYYY-MM-DD
Fine But why it has taken 1997 if I'm going to give 17 it will give as 2017.
If i give 37 it will give 2037 and if i give 67 and it is giving 1967 .
And lastly how can DD/MM/YYYY to YYYY-MM-DD Format

You need to use 103 when you specify four digit year:
SELECT CONVERT(DATE, '11/10/1997', 103)
-- 1997-10-11 (DATE)
If you want to convert the date back to a string, convert it again:
SELECT CONVERT(VARCHAR(10), CONVERT(DATE, '11/10/1997', 103), 120)
-- 1997-10-11 (VARCHAR)
Complete list of styles is available here.

Instead of 3 you can pun 103.
So :
SELECT CONVERT(CHAR(19), CONVERT(DATE, '11/10/1997', 103), 120); will return 1997-10-11

Can you try this?
declare #datechar as char(19) ='11/10/1997'
select FORMAT(convert(date,#datechar,103),'yyyy-MM-dd')

Related

Convert character string into this specific date format?

I am using SQL Server 2014 and I have a table (t1) which contain a column (ReviewDate) in the nvarchar format.
An example of a row of this column is given below:
ReviewDate
Mr John wrote a review in Oct 2017
I need to extract the "date" component from this character string.
To do this, my T-SQL is as follows:
SELECT (RIGHT([ReviewDate], 8)) as [ReviewDate 2]
FROM t1
This gives me "Oct 2017".
Now, I want to convert the "Oct 2017" into "2017-10-01" as a datetime format. This is where I am stuck.
I have tried the following:
SELECT CONVERT(datetime, (RIGHT([ReviewDate], 8)), 121) as [ReviewDate2]
Above syntax gives me the following error message: "Conversion failed when converting date and/or time from character string."
SELECT CAST( (RIGHT([ReviewDate], 8)) as datetime) as [ReviewDate2]
Above syntax gives me the same error message:
Conversion failed when converting date and/or time from character string.
Some help will be appreciated.
All your queries are right but make sure that, it should not have any other string apart from date part.
For example SELECT CAST('x Oct 2017' AS DATE) will give you error like
Conversion failed when converting date and/or time from character
string.
SELECT CAST((RIGHT('Mr John wrote a review in Oct 2017', 8)) as datetime) as [ReviewDate2]
SELECT CAST('Oct 2017' AS DATE)
SELECT CONVERT(DATETIME, 'Oct 2017 ', 121) as [ReviewDate2]
FIDDLE DEMO
so far your sample text is a valid datetime in mssql when I tried to cast. It seems there's some invalid data on your table. try using try_cast() to include those invalid data.
declare #ReviewDate varchar(max)='Mr John wrote a review in Oct 2017'
set #ReviewDate = (RIGHT(#ReviewDate, 8))
select try_cast(#ReviewDate as datetime) as [ReviewDate2]
dbfiddle<>

Converting Date Format in SQL Server - Getting Data Type Error

Trying to convert my date to a different format but running into issues.
Currently, my date column looks like:
YearBuilt
1934-01-01 00:00:00:0000
1981-01-01 00:00:00:0000
I'd like to have it be:
YearBuilt
01/01/1934 00:00:00:0000
01/01/1981 00:00:00:0000
I tried
update table set YearBuilt = '01/01/' + YearBuilt
But get the error:
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
But my YearBuilt column is already a datetime data type, so I'm not sure which string it's trying to convert.
Any input would be sincerely appreciated!
Date/times are stored in SQL in an internal format. That is a good thing! You should specify the format on output. That is, you can do:
select '01/01/' + datename(year, YearBuilt)
You can build this into the table:
alter table t add YearBuilt_str as ('01/01/' + datename(year, YearBuilt))
Then just use the string version to get the alternative format.
Try this:
DECLARE #D DateTime = '2017-11-01 00:00:00:000';
SELECT #D AS Input,
CONVERT(VARCHAR(50) , #D, 101) +
SUBSTRING(CONVERT(VARCHAR(50), #D, 113), 12, LEN(CONVERT(VARCHAR(30), #D, 113))) AS OutPut;
Result:
+---------------------+------------------------+
| Input | OutPut |
+---------------------+------------------------+
| 01.11.2017 00:00:00 | 1/11/2017 00:00:00:000 |
+---------------------+------------------------+
When your column has Date Time datatype, then you can't update the date with your custom date format.
But, you can select your date with your Custom format by SQL Query:
SELECT '01/01/'+CONVERT(VARCHAR(4), YEAR(YearBuilt))+' '+CONVERT(VARCHAR(MAX), CAST(YearBuilt AS TIME)) [YearBuilt]
FROM <table_name>;
Result :
YearBuilt
01/01/1934 00:00:00.0000000
01/01/1981 00:00:00.0000000

How to return till date part only from a SQL Server datetime datatype [duplicate]

SELECT GETDATE()
Returns: 2008-09-22 15:24:13.790
I want that date part without the time part: 2008-09-22 00:00:00.000
How can I get that?
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, #your_date))
for example
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
gives me
2008-09-22 00:00:00.000
Pros:
No varchar<->datetime conversions required
No need to think about locale
SQLServer 2008 now has a 'date' data type which contains only a date with no time component. Anyone using SQLServer 2008 and beyond can do the following:
SELECT CONVERT(date, GETDATE())
If using SQL 2008 and above:
select cast(getdate() as date)
DATEADD and DATEDIFF are better than CONVERTing to varchar. Both queries have the same execution plan, but execution plans are primarily about data access strategies and do not always reveal implicit costs involved in the CPU time taken to perform all the pieces. If both queries are run against a table with millions of rows, the CPU time using DateDiff can be close to 1/3rd of the Convert CPU time!
To see execution plans for queries:
set showplan_text on
GO
Both DATEADD and DATEDIFF will execute a CONVERT_IMPLICIT.
Although the CONVERT solution is simpler and easier to read for some, it is slower. There is no need to cast back to DateTime (this is implicitly done by the server). There is also no real need in the DateDiff method for DateAdd afterward as the integer result will also be implicitly converted back to DateTime.
SELECT CONVERT(varchar, MyDate, 101) FROM DatesTable
|--Compute Scalar(DEFINE:([Expr1004]=CONVERT(varchar(30),[TEST].[dbo].[DatesTable].[MyDate],101)))
|--Table Scan(OBJECT:([TEST].[dbo].[DatesTable]))
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, MyDate)) FROM DatesTable
|--Compute Scalar(DEFINE:([Expr1004]=dateadd(day,(0),CONVERT_IMPLICIT(datetime,datediff(day,'1900-01-01 00:00:00.000',CONVERT_IMPLICIT(datetime,[TEST].[dbo].[DatesTable].[MyDate],0)),0))))
|--Table Scan(OBJECT:([TEST].[dbo].[DatesTable]))
Using FLOOR() as #digi suggested has performance closer to DateDiff, but is not recommended as casting the DateTime data type to float and back does not always yield the original value.
Remember guys: Don't believe anyone. Look at the performance statistics, and test it yourself!
Be careful when you're testing your results. Selecting many rows to the client will hide the performance difference because it takes longer to send the rows over the network than it does to perform the calculations. So make sure that the work for all the rows is done by the server but there is no row set sent to the client.
There seems to be confusion for some people about when cache optimization affects queries. Running two queries in the same batch or in separate batches has no effect on caching. So you can either expire the cache manually or simply run the queries back and forth multiple times. Any optimization for query #2 would also affect any subsequent queries, so throw out execution #1 if you like.
Here is full test script and performance results that prove DateDiff is substantially faster than converting to varchar.
Try this:
SELECT CONVERT(VARCHAR(10),GETDATE(),111)
The above statement converts your current format to YYYY/MM/DD, please refer to this link to choose your preferable format.
SELECT CONVERT(datetime, CONVERT(varchar, GETDATE(), 101))
For return in date format
CAST(OrderDate AS date)
The above code will work in sql server 2010
It will return like 12/12/2013
For SQL Server 2012 use the below code
CONVERT(VARCHAR(10), OrderDate , 111)
Just do:
SELECT CAST(date_variable AS date)
or with with PostgreSQL:
SELECT date_variable::date
This is called typecasting btw!
You can use the CONVERT function to return only the date. See the link(s) below:
Date and Time Manipulation in SQL Server 2000
CAST and CONVERT
The syntax for using the convert function is:
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
If you need the result as a varchar, you should go through
SELECT CONVERT(DATE, GETDATE()) --2014-03-26
SELECT CONVERT(VARCHAR(10), GETDATE(), 111) --2014/03/26
which is already mentioned above.
If you need result in date and time format, you should use any of the queries below
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 111)) AS OnlyDate
2014-03-26 00:00:00.000
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 112)) AS OnlyDate
2014-03-26 00:00:00.000
DECLARE #OnlyDate DATETIME
SET #OnlyDate = DATEDIFF(DD, 0, GETDATE())
SELECT #OnlyDate AS OnlyDate
2014-03-26 00:00:00.000
If you are using SQL Server 2012 or above versions,
Use Format() function.
There are already multiple answers and formatting types for SQL server.
But most of the methods are somewhat ambiguous and it would be difficult for you to remember the numbers for format type or functions with respect to Specific Date Format. That's why in next versions of SQL server there is better option.
FORMAT ( value, format [, culture ] )
Culture option is very useful, as you can specify date as per your viewers.
You have to remember d (for small patterns) and D (for long patterns).
1."d" - Short date pattern.
2009-06-15T13:45:30 -> 6/15/2009 (en-US)
2009-06-15T13:45:30 -> 15/06/2009 (fr-FR)
2009-06-15T13:45:30 -> 2009/06/15 (ja-JP)
2."D" - Long date pattern.
2009-06-15T13:45:30 -> Monday, June 15, 2009 (en-US)
2009-06-15T13:45:30 -> 15 июня 2009 г. (ru-RU)
2009-06-15T13:45:30 -> Montag, 15. Juni 2009 (de-DE)
More examples in query.
DECLARE #d DATETIME = '10/01/2011';
SELECT FORMAT ( #d, 'd', 'en-US' ) AS 'US English Result'
,FORMAT ( #d, 'd', 'en-gb' ) AS 'Great Britain English Result'
,FORMAT ( #d, 'd', 'de-de' ) AS 'German Result'
,FORMAT ( #d, 'd', 'zh-cn' ) AS 'Simplified Chinese (PRC) Result';
SELECT FORMAT ( #d, 'D', 'en-US' ) AS 'US English Result'
,FORMAT ( #d, 'D', 'en-gb' ) AS 'Great Britain English Result'
,FORMAT ( #d, 'D', 'de-de' ) AS 'German Result'
,FORMAT ( #d, 'D', 'zh-cn' ) AS 'Chinese (Simplified PRC) Result';
US English Result Great Britain English Result German Result Simplified Chinese (PRC) Result
---------------- ----------------------------- ------------- -------------------------------------
10/1/2011 01/10/2011 01.10.2011 2011/10/1
US English Result Great Britain English Result German Result Chinese (Simplified PRC) Result
---------------------------- ----------------------------- ----------------------------- ---------------------------------------
Saturday, October 01, 2011 01 October 2011 Samstag, 1. Oktober 2011 2011年10月1日
If you want more formats, you can go to:
Standard Date and Time Format Strings
Custom Date and Time Format Strings
SELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),103) --21/09/2011
SELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),101) --09/21/2011
SELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),111) --2011/09/21
SELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),107) --Sep 21, 2011
Using FLOOR() - just cut time part.
SELECT CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)
To obtain the result indicated, I use the following command.
SELECT CONVERT(DATETIME,CONVERT(DATE,GETDATE()))
I holpe it is useful.
IF you want to use CONVERT and get the same output as in the original question posed, that is, yyyy-mm-dd then use CONVERT(varchar(10),[SourceDate as dateTime],121) same code as the previous couple answers, but the code to convert to yyyy-mm-dd with dashes is 121.
If I can get on my soapbox for a second, this kind of formatting doesn't belong in the data tier, and that's why it wasn't possible without silly high-overhead 'tricks' until SQL Server 2008 when actual datepart data types are introduced. Making such conversions in the data tier is a huge waste of overhead on your DBMS, but more importantly, the second you do something like this, you have basically created in-memory orphaned data that I assume you will then return to a program. You can't put it back in to another 3NF+ column or compare it to anything typed without reverting, so all you've done is introduced points of failure and removed relational reference.
You should ALWAYS go ahead and return your dateTime data type to the calling program and in the PRESENTATION tier, make whatever adjustments are necessary. As soon as you go converting things before returning them to the caller, you are removing all hope of referential integrity from the application. This would prevent an UPDATE or DELETE operation, again, unless you do some sort of manual reversion, which again is exposing your data to human/code/gremlin error when there is no need.
SELECT DATEADD(DD, DATEDIFF(DD, 0, GETDATE()), 0)
SELECT DATEADD(DAY, 0, DATEDIFF(DAY,0, GETDATE()))
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 101))
Edit: The first two methods are essentially the same, and out perform the convert to varchar method.
If you are assigning the results to a column or variable, give it the DATE type, and the conversion is implicit.
DECLARE #Date DATE = GETDATE()
SELECT #Date --> 2017-05-03
Convert(nvarchar(10), getdate(), 101) ---> 5/12/14
Convert(nvarchar(12), getdate(), 101) ---> 5/12/2014
Date:
SELECT CONVERT(date, GETDATE())
SELECT CAST(GETDATE() as date)
Time:
SELECT CONVERT(time , GETDATE() , 114)
SELECT CAST(GETDATE() as time)
Syntax:
SELECT CONVERT (data_type(length)),Date, DateFormatCode)
Ex:
Select CONVERT(varchar,GETDATE(),1) as [MM/DD/YY]
Select CONVERT(varchar,GETDATE(),2) as [YY.MM.DD]
all dateformatcodes about Date:
DateFormatCode Format
1 [MM/DD/YY]
2 [YY.MM.DD]
3 [DD/MM/YY]
4 [DD.MM.YY]
5 [DD-MM-YY]
6 [DD MMM YY]
7 [MMM DD,YY]
10 [MM-DD-YY]
11 [YY/MM/DD]
12 [YYMMDD]
23 [yyyy-mm-dd]
101 [MM/DD/YYYY]
102 [YYYY.MM.DD]
103 [DD/MM/YYYY]
104 [DD/MM/YYYY]
105 [DD/MM/YYYY]
106 [DD MMM YYYY]
107 [MMM DD,YYYY]
110 [MM-DD-YYYY]
111 [YYYY/MM/DD]
112 [YYYYMMDD]
Simply you can do this way:
SELECT CONVERT(date, getdate())
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, #your_date))
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
Outputs as:
2008-09-22 00:00:00.000
Or simply do like this:
SELECT CONVERT (DATE, GETDATE()) 'Date Part Only'
Result:
Date Part Only
--------------
2013-07-14
In this case, date only, you we are gonna run this query:
SELECT CONVERT(VARCHAR(10), getdate(), 111);
I think this would work in your case:
CONVERT(VARCHAR(10),Person.DateOfBirth,111) AS BirthDate
//here date is obtained as 1990/09/25
DECLARE #yourdate DATETIME = '11/1/2014 12:25pm'
SELECT CONVERT(DATE, #yourdate)
Okay, Though I'm bit late :), Here is the another solution.
SELECT CAST(FLOOR(CAST(GETDATE() AS FLOAT)) as DATETIME)
Result
2008-09-22 00:00:00.000
And if you are using SQL Server 2012 and higher then you can use FORMAT() function like this -
SELECT FORMAT(GETDATE(), 'yyyy-MM-dd')
Starting from SQL SERVER 2012, you can do this:
SELECT FORMAT(GETDATE(), 'yyyy-MM-dd 00:00:00.000')
Even using the ancient MSSQL Server 7.0, the code here (courtesy of this link) allowed me to get whatever date format I was looking for at the time:
PRINT '1) Date/time in format MON DD YYYY HH:MI AM (OR PM): ' + CONVERT(CHAR(19),GETDATE())
PRINT '2) Date/time in format MM-DD-YY: ' + CONVERT(CHAR(8),GETDATE(),10)
PRINT '3) Date/time in format MM-DD-YYYY: ' + CONVERT(CHAR(10),GETDATE(),110)
PRINT '4) Date/time in format DD MON YYYY: ' + CONVERT(CHAR(11),GETDATE(),106)
PRINT '5) Date/time in format DD MON YY: ' + CONVERT(CHAR(9),GETDATE(),6)
PRINT '6) Date/time in format DD MON YYYY HH:MM:SS:MMM(24H): ' + CONVERT(CHAR(24),GETDATE(),113)
It produced this output:
1) Date/time in format MON DD YYYY HH:MI AM (OR PM): Feb 27 2015 1:14PM
2) Date/time in format MM-DD-YY: 02-27-15
3) Date/time in format MM-DD-YYYY: 02-27-2015
4) Date/time in format DD MON YYYY: 27 Feb 2015
5) Date/time in format DD MON YY: 27 Feb 15
6) Date/time in format DD MON YYYY HH:MM:SS:MMM(24H): 27 Feb 2015 13:14:46:630
why don't you use DATE_FORMAT( your_datetiem_column, '%d-%m-%Y' ) ?
EX: select DATE_FORMAT( some_datetime_column, '%d-%m-%Y' ) from table_name
you can change sequence of m,d and year by re-arranging '%d-%m-%Y' part
I know this is old, but I do not see where anyone stated it this way. From what I can tell, this is ANSI standard.
SELECT CAST(CURRENT_TIMESTAMP AS DATE)
It would be good if Microsoft could also support the ANSI standard CURRENT_DATE variable.
I favor the following which wasn't mentioned:
DATEFROMPARTS(DATEPART(yyyy, #mydatetime), DATEPART(mm, #mydatetime), DATEPART(dd, #mydatetime))
It also doesn't care about local or do a double convert -- although each 'datepart' probably does math. So it may be a little slower than the datediff method, but to me it is much more clear. Especially when I want to group by just the year and month (set the day to 1).

Date conversion issue.: yyyy/MM/dd to dd/MM/yyyy

I have a date column where the date format is
2010-04-14
in SQL Server. Is there any possible way to retrieve the date format as
14/04/2010
in a select statement?
Try this:
SELECT CONVERT(VARCHAR(10), GETDATE(), 103) AS [DD/MM/YYYY]
Source Link
Addendum 1:
As described in my comment, you need to convert your field to a DATETIME type before the above will work. This example should work on your SQL Server:
SELECT CONVERT(VARCHAR(10), CAST('2010-04-14' AS DATETIME), 103) AS [DD/MM/YYYY]
If you get this exception:
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.
Then you need to change your date field to be in YYYY-MM-DD Format, EG: 2010-14-04
OR
Add the following line before the select statement:
SET DATEFORMAT MDY -- Input dates are in the MM/DD/YYYY format, change to DMY to handle UK dates
Example:
SET DATEFORMAT MDY;
SELECT CONVERT(VARCHAR(10), CAST('2010-04-14' AS DATETIME), 103) AS [DD/MM/YYYY]
Another way to solve your problem:
select substring(columnName, 9, 2) + '/' + substring(columnName, 6, 2) + '/' + substring(columnName, 1, 4)
If you are displaying that date outside of SqlServer, a better way would be to retrieve that date as date and convert it to the string-representation you want just before displaying it.
How to do that depends on your situation.
select replace(datetime,'-','/')

How to return only the Date from a SQL Server DateTime datatype

SELECT GETDATE()
Returns: 2008-09-22 15:24:13.790
I want that date part without the time part: 2008-09-22 00:00:00.000
How can I get that?
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, #your_date))
for example
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
gives me
2008-09-22 00:00:00.000
Pros:
No varchar<->datetime conversions required
No need to think about locale
SQLServer 2008 now has a 'date' data type which contains only a date with no time component. Anyone using SQLServer 2008 and beyond can do the following:
SELECT CONVERT(date, GETDATE())
If using SQL 2008 and above:
select cast(getdate() as date)
DATEADD and DATEDIFF are better than CONVERTing to varchar. Both queries have the same execution plan, but execution plans are primarily about data access strategies and do not always reveal implicit costs involved in the CPU time taken to perform all the pieces. If both queries are run against a table with millions of rows, the CPU time using DateDiff can be close to 1/3rd of the Convert CPU time!
To see execution plans for queries:
set showplan_text on
GO
Both DATEADD and DATEDIFF will execute a CONVERT_IMPLICIT.
Although the CONVERT solution is simpler and easier to read for some, it is slower. There is no need to cast back to DateTime (this is implicitly done by the server). There is also no real need in the DateDiff method for DateAdd afterward as the integer result will also be implicitly converted back to DateTime.
SELECT CONVERT(varchar, MyDate, 101) FROM DatesTable
|--Compute Scalar(DEFINE:([Expr1004]=CONVERT(varchar(30),[TEST].[dbo].[DatesTable].[MyDate],101)))
|--Table Scan(OBJECT:([TEST].[dbo].[DatesTable]))
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, MyDate)) FROM DatesTable
|--Compute Scalar(DEFINE:([Expr1004]=dateadd(day,(0),CONVERT_IMPLICIT(datetime,datediff(day,'1900-01-01 00:00:00.000',CONVERT_IMPLICIT(datetime,[TEST].[dbo].[DatesTable].[MyDate],0)),0))))
|--Table Scan(OBJECT:([TEST].[dbo].[DatesTable]))
Using FLOOR() as #digi suggested has performance closer to DateDiff, but is not recommended as casting the DateTime data type to float and back does not always yield the original value.
Remember guys: Don't believe anyone. Look at the performance statistics, and test it yourself!
Be careful when you're testing your results. Selecting many rows to the client will hide the performance difference because it takes longer to send the rows over the network than it does to perform the calculations. So make sure that the work for all the rows is done by the server but there is no row set sent to the client.
There seems to be confusion for some people about when cache optimization affects queries. Running two queries in the same batch or in separate batches has no effect on caching. So you can either expire the cache manually or simply run the queries back and forth multiple times. Any optimization for query #2 would also affect any subsequent queries, so throw out execution #1 if you like.
Here is full test script and performance results that prove DateDiff is substantially faster than converting to varchar.
Try this:
SELECT CONVERT(VARCHAR(10),GETDATE(),111)
The above statement converts your current format to YYYY/MM/DD, please refer to this link to choose your preferable format.
SELECT CONVERT(datetime, CONVERT(varchar, GETDATE(), 101))
For return in date format
CAST(OrderDate AS date)
The above code will work in sql server 2010
It will return like 12/12/2013
For SQL Server 2012 use the below code
CONVERT(VARCHAR(10), OrderDate , 111)
Just do:
SELECT CAST(date_variable AS date)
or with with PostgreSQL:
SELECT date_variable::date
This is called typecasting btw!
You can use the CONVERT function to return only the date. See the link(s) below:
Date and Time Manipulation in SQL Server 2000
CAST and CONVERT
The syntax for using the convert function is:
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
If you need the result as a varchar, you should go through
SELECT CONVERT(DATE, GETDATE()) --2014-03-26
SELECT CONVERT(VARCHAR(10), GETDATE(), 111) --2014/03/26
which is already mentioned above.
If you need result in date and time format, you should use any of the queries below
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 111)) AS OnlyDate
2014-03-26 00:00:00.000
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 112)) AS OnlyDate
2014-03-26 00:00:00.000
DECLARE #OnlyDate DATETIME
SET #OnlyDate = DATEDIFF(DD, 0, GETDATE())
SELECT #OnlyDate AS OnlyDate
2014-03-26 00:00:00.000
If you are using SQL Server 2012 or above versions,
Use Format() function.
There are already multiple answers and formatting types for SQL server.
But most of the methods are somewhat ambiguous and it would be difficult for you to remember the numbers for format type or functions with respect to Specific Date Format. That's why in next versions of SQL server there is better option.
FORMAT ( value, format [, culture ] )
Culture option is very useful, as you can specify date as per your viewers.
You have to remember d (for small patterns) and D (for long patterns).
1."d" - Short date pattern.
2009-06-15T13:45:30 -> 6/15/2009 (en-US)
2009-06-15T13:45:30 -> 15/06/2009 (fr-FR)
2009-06-15T13:45:30 -> 2009/06/15 (ja-JP)
2."D" - Long date pattern.
2009-06-15T13:45:30 -> Monday, June 15, 2009 (en-US)
2009-06-15T13:45:30 -> 15 июня 2009 г. (ru-RU)
2009-06-15T13:45:30 -> Montag, 15. Juni 2009 (de-DE)
More examples in query.
DECLARE #d DATETIME = '10/01/2011';
SELECT FORMAT ( #d, 'd', 'en-US' ) AS 'US English Result'
,FORMAT ( #d, 'd', 'en-gb' ) AS 'Great Britain English Result'
,FORMAT ( #d, 'd', 'de-de' ) AS 'German Result'
,FORMAT ( #d, 'd', 'zh-cn' ) AS 'Simplified Chinese (PRC) Result';
SELECT FORMAT ( #d, 'D', 'en-US' ) AS 'US English Result'
,FORMAT ( #d, 'D', 'en-gb' ) AS 'Great Britain English Result'
,FORMAT ( #d, 'D', 'de-de' ) AS 'German Result'
,FORMAT ( #d, 'D', 'zh-cn' ) AS 'Chinese (Simplified PRC) Result';
US English Result Great Britain English Result German Result Simplified Chinese (PRC) Result
---------------- ----------------------------- ------------- -------------------------------------
10/1/2011 01/10/2011 01.10.2011 2011/10/1
US English Result Great Britain English Result German Result Chinese (Simplified PRC) Result
---------------------------- ----------------------------- ----------------------------- ---------------------------------------
Saturday, October 01, 2011 01 October 2011 Samstag, 1. Oktober 2011 2011年10月1日
If you want more formats, you can go to:
Standard Date and Time Format Strings
Custom Date and Time Format Strings
SELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),103) --21/09/2011
SELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),101) --09/21/2011
SELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),111) --2011/09/21
SELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),107) --Sep 21, 2011
Using FLOOR() - just cut time part.
SELECT CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)
To obtain the result indicated, I use the following command.
SELECT CONVERT(DATETIME,CONVERT(DATE,GETDATE()))
I holpe it is useful.
IF you want to use CONVERT and get the same output as in the original question posed, that is, yyyy-mm-dd then use CONVERT(varchar(10),[SourceDate as dateTime],121) same code as the previous couple answers, but the code to convert to yyyy-mm-dd with dashes is 121.
If I can get on my soapbox for a second, this kind of formatting doesn't belong in the data tier, and that's why it wasn't possible without silly high-overhead 'tricks' until SQL Server 2008 when actual datepart data types are introduced. Making such conversions in the data tier is a huge waste of overhead on your DBMS, but more importantly, the second you do something like this, you have basically created in-memory orphaned data that I assume you will then return to a program. You can't put it back in to another 3NF+ column or compare it to anything typed without reverting, so all you've done is introduced points of failure and removed relational reference.
You should ALWAYS go ahead and return your dateTime data type to the calling program and in the PRESENTATION tier, make whatever adjustments are necessary. As soon as you go converting things before returning them to the caller, you are removing all hope of referential integrity from the application. This would prevent an UPDATE or DELETE operation, again, unless you do some sort of manual reversion, which again is exposing your data to human/code/gremlin error when there is no need.
SELECT DATEADD(DD, DATEDIFF(DD, 0, GETDATE()), 0)
SELECT DATEADD(DAY, 0, DATEDIFF(DAY,0, GETDATE()))
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 101))
Edit: The first two methods are essentially the same, and out perform the convert to varchar method.
If you are assigning the results to a column or variable, give it the DATE type, and the conversion is implicit.
DECLARE #Date DATE = GETDATE()
SELECT #Date --> 2017-05-03
Convert(nvarchar(10), getdate(), 101) ---> 5/12/14
Convert(nvarchar(12), getdate(), 101) ---> 5/12/2014
Date:
SELECT CONVERT(date, GETDATE())
SELECT CAST(GETDATE() as date)
Time:
SELECT CONVERT(time , GETDATE() , 114)
SELECT CAST(GETDATE() as time)
Syntax:
SELECT CONVERT (data_type(length)),Date, DateFormatCode)
Ex:
Select CONVERT(varchar,GETDATE(),1) as [MM/DD/YY]
Select CONVERT(varchar,GETDATE(),2) as [YY.MM.DD]
all dateformatcodes about Date:
DateFormatCode Format
1 [MM/DD/YY]
2 [YY.MM.DD]
3 [DD/MM/YY]
4 [DD.MM.YY]
5 [DD-MM-YY]
6 [DD MMM YY]
7 [MMM DD,YY]
10 [MM-DD-YY]
11 [YY/MM/DD]
12 [YYMMDD]
23 [yyyy-mm-dd]
101 [MM/DD/YYYY]
102 [YYYY.MM.DD]
103 [DD/MM/YYYY]
104 [DD/MM/YYYY]
105 [DD/MM/YYYY]
106 [DD MMM YYYY]
107 [MMM DD,YYYY]
110 [MM-DD-YYYY]
111 [YYYY/MM/DD]
112 [YYYYMMDD]
Simply you can do this way:
SELECT CONVERT(date, getdate())
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, #your_date))
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
Outputs as:
2008-09-22 00:00:00.000
Or simply do like this:
SELECT CONVERT (DATE, GETDATE()) 'Date Part Only'
Result:
Date Part Only
--------------
2013-07-14
In this case, date only, you we are gonna run this query:
SELECT CONVERT(VARCHAR(10), getdate(), 111);
I think this would work in your case:
CONVERT(VARCHAR(10),Person.DateOfBirth,111) AS BirthDate
//here date is obtained as 1990/09/25
DECLARE #yourdate DATETIME = '11/1/2014 12:25pm'
SELECT CONVERT(DATE, #yourdate)
Okay, Though I'm bit late :), Here is the another solution.
SELECT CAST(FLOOR(CAST(GETDATE() AS FLOAT)) as DATETIME)
Result
2008-09-22 00:00:00.000
And if you are using SQL Server 2012 and higher then you can use FORMAT() function like this -
SELECT FORMAT(GETDATE(), 'yyyy-MM-dd')
Starting from SQL SERVER 2012, you can do this:
SELECT FORMAT(GETDATE(), 'yyyy-MM-dd 00:00:00.000')
Even using the ancient MSSQL Server 7.0, the code here (courtesy of this link) allowed me to get whatever date format I was looking for at the time:
PRINT '1) Date/time in format MON DD YYYY HH:MI AM (OR PM): ' + CONVERT(CHAR(19),GETDATE())
PRINT '2) Date/time in format MM-DD-YY: ' + CONVERT(CHAR(8),GETDATE(),10)
PRINT '3) Date/time in format MM-DD-YYYY: ' + CONVERT(CHAR(10),GETDATE(),110)
PRINT '4) Date/time in format DD MON YYYY: ' + CONVERT(CHAR(11),GETDATE(),106)
PRINT '5) Date/time in format DD MON YY: ' + CONVERT(CHAR(9),GETDATE(),6)
PRINT '6) Date/time in format DD MON YYYY HH:MM:SS:MMM(24H): ' + CONVERT(CHAR(24),GETDATE(),113)
It produced this output:
1) Date/time in format MON DD YYYY HH:MI AM (OR PM): Feb 27 2015 1:14PM
2) Date/time in format MM-DD-YY: 02-27-15
3) Date/time in format MM-DD-YYYY: 02-27-2015
4) Date/time in format DD MON YYYY: 27 Feb 2015
5) Date/time in format DD MON YY: 27 Feb 15
6) Date/time in format DD MON YYYY HH:MM:SS:MMM(24H): 27 Feb 2015 13:14:46:630
why don't you use DATE_FORMAT( your_datetiem_column, '%d-%m-%Y' ) ?
EX: select DATE_FORMAT( some_datetime_column, '%d-%m-%Y' ) from table_name
you can change sequence of m,d and year by re-arranging '%d-%m-%Y' part
I know this is old, but I do not see where anyone stated it this way. From what I can tell, this is ANSI standard.
SELECT CAST(CURRENT_TIMESTAMP AS DATE)
It would be good if Microsoft could also support the ANSI standard CURRENT_DATE variable.
I favor the following which wasn't mentioned:
DATEFROMPARTS(DATEPART(yyyy, #mydatetime), DATEPART(mm, #mydatetime), DATEPART(dd, #mydatetime))
It also doesn't care about local or do a double convert -- although each 'datepart' probably does math. So it may be a little slower than the datediff method, but to me it is much more clear. Especially when I want to group by just the year and month (set the day to 1).