简体   繁体   中英

T-SQL Dates using Convert() function?

I am bit confusing here?

declare @date1 datetime = '2016-01-21 14:10:47.183'

I want to convert '2016-01-21 14:10:47.183' To '21-01-2016'

when I tried: select convert(date,@date1,105) I am getting: 2016-01-21

But with: select convert(varchar(10),@date1,105) I am getting: 21-01-2016

Why I am not having same results with above code?

Why should I convert to varchar ?

Thanks in advance

This is just presentation matter and should be done in application layer. If you cannot do it in application you could use FORMAT (SQL Server 2012+):

declare @date1 datetime = '2016-01-21 14:10:47.183'

SELECT FORMAT(@date1, 'dd-mm-yyyy');

LiveDemo


Why I am not having same results with above code?

select convert(date,@date1,105)
-- DATETIME -> DATE
-- vs
select convert(varchar(10),@date1,105)
-- DATETIME -> VARCHAR(10) using specific style

If you only to skip time part use SELECT CAST(@date1 AS DATE) and do not bother how it is presented. It is still DATE .

To sum up: in SQL query use DATE as date, in application display it with desired format.

The reason why is because once you put a value in a datetime column (or date or any of the other variations on date-time datatypes) in SQL Server. SQL Server ceases to think of that date as having any particular format. It translates it into numbers, and stores it that way internally.

So when you select a date from a date time column, SQL Server displays it in the default format that you have selected based on your environment/local settings.

If you want to display it in any other format, you have to first convert it to a string, because as far as SQL Server is concerned, dates don't have formats. They are just numbers. The 21st day of March is the 21st day of March, whether you write it as 3/21 or 21/3.

So when you try to convert a date to a date with a different format, SQL Server just ignores you because dates don't have formats. However, if you want to convert that date to a string, SQL Server will be happy to help you display that string in any format you like.

Hope this helps, but sounds like some further research into how SQL Server stores dates would help your understanding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM