Format date as yyyy-mm-dd hh:mm:ss.000 - sql

I have this date: 7/19/2013
I want to format it as the following:
2013-07-19 00:00:00.000
I tried this:
select convert(varchar(10),'7/19/2013',120)
But it is giving me the same result!

You need to tell SQL Server it's a date; otherwise, it just sees a string, and ignores the style number since it's not relevant for a string. As Steve Kass pointed out, the code is only truly portable if you protect the incoming string from incorrect regional- or language-based translations (such as d/m/y - which could lead to an error or, even worse, the wrong data). I've updated the code to interpret the string as m/d/y regardless of locale, but if you're on SQL Server 2012 you could also use PARSE() as in his example (or TRY_PARSE() if you want to essentially ignore invalid dates).
And if you want the time attached including milliseconds, you need to allow more than 10 characters, and a style that supports milliseconds.
SELECT CONVERT(CHAR(23),CONVERT(DATETIME,'7/19/2013',101),121);
Result:
2013-07-19 00:00:00.000
If you don't care about milliseconds, you can use style 120 instead:
SELECT CONVERT(CHAR(19),CONVERT(DATETIME,'7/19/2013',101),120);
And if you don't care about seconds, you can truncate earlier:
SELECT CONVERT(CHAR(16),CONVERT(DATETIME,'7/19/2013',101),120);

Note that Aaron's solution will fail if the server is localized to a language with DMY as the date format. This is because the inner CONVERT in Aaron's example will incorporate the server locale, which may not be what you expect.
To make this bulletproof (assuming the source of the string doesn't automatically re-localize the format), convert the string with PARSE (requires SQL Server 2012 or later).
SET LANGUAGE English
SELECT CONVERT(CHAR(23),TRY_CONVERT(DATETIME,'7/19/2013'),121);
SELECT CONVERT(CHAR(23),PARSE('7/19/2013' AS DATETIME USING 'en-US'),121);
SET LANGUAGE Français
SELECT CONVERT(CHAR(23),TRY_CONVERT(DATETIME,'7/19/2013'),121);
SELECT CONVERT(CHAR(23),PARSE('7/19/2013' AS DATETIME USING 'en-US'),121);

Adding to your query, you can just add the Zeros/the characters as you want :)...
SELECT CONVERT(VARCHAR (10),'7/19/2013',120) + ' 00:00:00.000'
Result:
7/19/2013 00:00:00.000

Related

String to datetime conversion in sql server

Is it possible to convert 'OCT-20' to '2020/10/01' in sql server. I tried the following cases without any luck.
select convert(date, 'OCT-20',103)
----Conversion failed when converting date and/or time from character string.
alter table MyTable alter column [period] date
----Conversion failed when converting date and/or time from character string.
I am using sql server 2016.
If we assume that the value is always in the format MMM-yy then you could do this:
SELECT CONVERT(date,'01-' + StringDate,106)
FROM dbo.YourTable;
Of course, this has 2 flaws.
The date uses a 2 digit year, so SQL Server could assume the wrong century
It'll only work if the LOGIN is using an English based language, otherwise it'll fail.
The real solution is to fix your design; never store date (and time) values in a varchar, and when ever you do use a varchar for a date (such as a literal in a WHERE) use an unambiguous format such as yyyyMMdd or yyyy-MM-ddThh:mm:ss.nnnnnnn.

Date format on query different from date format in result

I wrote a SQL query to have the results from 2016 Apr 01 to 2016 May 01.
When I wrote:
where a.DateIntervention >= '2016-04-01'
and a.DateIntervention < '2016-05-01'
I obtain the results from 2016 Jan 04 00:00:00.000, so it is reading my dates as ydm, although the results show the date format as ymd (2016-01-04 00:00:00.000)
And when I ask the system about the date format it tells me it is dmy (!)
How to change this setting so that I can write my queries like ymd and continue obtaining the results like ymd?
In SQL Server, you don't need to. If you drop the hyphens then the strings will be interpreted using YYYYMMDD:
where a.DateIntervention >= '20160401' and a.DateIntervention < '20160501'
I prefer the hyphens because they are more readable, accepted in most databases, and generally work in SQL Server. There are particular settings where they don't work, but 'YYYYMMDD' is always interpreted as a date.
I should add, you can throw in a cast()/convert() if you like:
where a.DateIntervention >= cast('20160401' as date) and
a.DateIntervention < cast('20160501' as date)
There's no built-in way for the query to realize "I was supplied a YMD date, I should output dates as YMD too.".
In theory you could call SET DATEFORMAT ymd, but I mislike that because it might affect something farther down the line you don't know about.
If you want an explicit formatting/parsing style during conversion (which is almost always a good idea), you need to explicitly convert it, and supply the style:
-- 126 is hyphenated, but has extra parts if something other than date is used
CONVERT(DATE, '2017-07-28', 126)
Of course, the best option is to supply the parameter as an actual DATE type, and get output the same way, which saves you from converting back and forth to a string type, and avoids the formatting problem. This may not be available in a cases, however (like ad hoc queries).

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.

Why does SQL Server convert VARCHAR to DATETIME using an invalid style?

I can't make out from the documentation why SQL Server parses a text in a format other than the specified style.
Regardless of whether I provide text in the expected format:
SELECT CONVERT(DATETIME, N'20150601', 112)
or incorrect format (for style 113):
SELECT CONVERT(DATETIME, N'20150601', 113)
The results are the same: 2015-06-01 00:00:00.000 I would expect the latter to fail to convert the date (correctly).
What rules does it employ when trying to convert a VARCHAR to DATETIME? I.e. why does the latter (incorrect format style) still correctly parse the date?
EDIT: It seems I've not been clear enough. Style 113 should expect dd mon yyyy hh:mi:ss:mmm(24h) but it happily converts values in the format yyyymmdd for some reason.
Because the date is in a canonical format ie(20150101). The database engine falls over it implicitly. This is a compatibility feature.
If you swapped these around to UK or US date formats, you would receive conversion errors, because they cannot be implicitly converted.
EDIT: You could actually tell it to convert it to a pig, and it would still implicitly convert it to date time:
select convert(datetime,'20150425',99999999)
select convert(datetime,'20150425',100)
select convert(datetime,'20150425',113)
select convert(datetime,'20150425',010)
select convert(datetime,'20150425',8008135)
select convert(datetime,'20150425',000)
And proof of concept that this is a compatibility feature:
select convert(datetime2,'20150425',99999999)
Although you can still implicitly convert datetime2 objects, but the style must be in the scope of the conversion chart.
Reason why is the date N'20150601' converted to valid datetime is because of fact that literal N'20150601' is universal notation of datetime in SQL Server. That means, if you state datetime value in format N'yyyymmdd', SQL Server know that it is universal datetime format and know how to read it, in which order.
You should convert to varchar type in order to apply those formats:
SELECT CONVERT(varchar(100), CAST('20150601' as date), 113)
OK, you are converting datetime to datetime. What did you expect? In order to apply formats you should convert to varchar and you have to have date or time type as second parameter.

SQL Server date format MM/DD/YYYY

How do I check if a date string is in the MM/DD/YYYY format in SQL Server?
SET DATEFORMAT MDY;
SELECT CASE WHEN ISDATE(#string) = 1
AND #string LIKE '[0-1][0-9]/[0-3][0-9]/[1-2][0-9][0-9][0-9]'
THEN 1 ELSE 0 END;
If the result is 1, it's a valid date, but there's no guarantee that it's the date the user meant. If they enter:
06/07/2012
There is no way to know if they meant June 7 or July 6. Your best bet is to make users pick dates from drop-downs or calendar controls, which allows you to control the format and avoid any needless interpretation. Your application layer can use strongly typed variables / parameters and insert into properly typed columns.
If you're after the SQL Server dateformat to see whether it's MDY then use:
dbcc useroptions
And have a look at the dateformat Set Option
you convert date to datestring in this format MM/DD/YYYY using CONVERT function
select convert(varchar(10),getdate(),101)
The output will be as of Sept 8th 2012
09/08/2012
There is no need to validate, other then checking the date field is null or not
You have to do it outside the database. A database stores datetime internally in its own format. I dont think you can read what format the date is stored in. You can read it which ever way you like, for example dd/mm/yyyy or yyyy/mm/dd etc.
What you can do is check this value outside the database for any date field. You can use regular expression for that. But that will be outside the database.