SQL Server date format MM/DD/YYYY - sql

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.

Related

Date format value not updating from previous format to new format after update

When I update a column from a table with a date format of MMM DD,YYYY to a new format. The format doesn't change to the desired format which is YYYY-MM-DD HH:MM:SS. Even when update different value like GETDATE(). The date will change but the format will remain the same.
Current value & format from column the type is varchar
DueDate
Jun 27 2020 12:00AM
Desired format
DueDate
2020-06-27 00:00:00.000
Update statement
update TableName
set
DueDate = CAST([DueDate] AS smalldatetime),
LastSyncDateTime = GETDATE()
where CaseGuid = 'DA2CE6A1-0394-463E-8E8D-962F3A24ADC8'
There is a huge confusion between "Date displaying format" and "Date storing format". The VERY short explanation is that what you mentioned is only a client side displaying format, while SQL Server have specific format which is used for storing dates (remember that the server stores zero and one only).
You can insert dates to a table using different styles (the official name for the displaying format is STYLE), and you can present the dates in the client side using different style, but it will always be stored the same from the "SQL Server point of view" according to the DATE type which is used.
In order to solve your original needs, all that you needed to do is to provide the server the information about the style which you use in the client side (in the query). This is done by using explicit CONVERT with the third parameter, which is the STYLE.
For example if you use in the client side an Israeli format like dd/MM/yyyy, then you should use CONVERT(DATE, '27/02/2021', 103).
For more information on different STYLEs you can check this documentation.
Note: If you want to display the dates in specific format which is not covered by the existing STYLEs then you can use the function FORMAT() in your query. This function is fully flexible to return the data in your specific format. Remember that this function returns the data as string and it will not be date anymore.
For example, let's say that I want to use the format: "Day:dd,Month:MM,Year:yyyy". So if the date is '27/02/2021' then I expect to get "Day:27,Month:02,Year:2021". In this case use below:
DECLARE #D DATE
SET #D = CONVERT(DATE, '27/02/2021', 103) -- convert string to date for storing
select FORMAT(#D, 'Day:dd, Month:MM, Year:yyyy') -- convert date to string for displaying
Solution use the format function
update TableName
set
DueDate = FORMAT (CAST([DueDate] AS smalldatetime),'yyyy-MM-dd HH:mm:ss'),
LastSyncDateTime = GETDATE()
where CaseGuid = 'DA2CE6A1-0394-463E-8E8D-962F3A24ADC8'
https://www.sqlshack.com/a-comprehensive-guide-to-the-sql-format-function/

Why procedure throws error if I pass it date i.e. 20/04/2020?

I am using this
CAST(NotifDate as date) between #FromNotifDate AND #ToNotifDate
but NotifDate is saved as varchar in table but FromNotifDate AND ToNotifDate are of Date type.
When I pass these parameters 08/06/2014 and 20/04/2020 09:40:17 it doesn't work and throws error i.e.
Conversion failed when converting date and/or time from character string.
but if I pass 08/06/2014 and 10/04/2020 09:40:17 it works.
Your current database locale settings are probably set to en-US or another where the date format is MM/dd/yyyy.
That makes 08/06/2014 and 10/04/2014 valid dates (but they are 6th of August and 4th of October, not 8th of June and 10th of April!), but not 20/04/2020.
To use a different date format, you can use CONVERT, with the proper style code (I believe it's 103 for dd/MM/yyyy (see documentation)
So, this should work for you : CONVERT(date, NotifDate, 103)
Note that, as a general recommendation, it would be beneficial that you input NotifDate as a proper SQL Date in your DB in the first place, if possible, to avoid having to do conversion like this in your queries.
Also, there the unambiguous and international standard ISO-8601 format yyyy-MM-dd which should be always parsed correctly by CAST, I recommend using it over any localized format where you can in your code infrastructure.
System having default date format is "MM/dd/yyyy" so while you set "10/04/2020 09:40:17" value so system throm an Error- out of range Error,
-- The conversion of a varchar data type
-- to a datetime data type resulted in an out-of-range value.
select cast('20/04/2020 09:40:17' as datetime)
-- get the current session date_format
select date_format
from sys.dm_exec_sessions
where session_id = ##spid
-- set the dateformat for the current session
set dateformat dmy
-- this should work
select cast('20/04/2020 09:40:17' as datetime)

SQL Table datetime column format

I tried googling to get an answer but in vain. Below is my requirement
User has an option to insert data into a table which has export_date as datetime
When they execute insert statements, I want to ensure that they have keyed in date in "dd-MM-yyyy hh:mm:ss" format. If not, don't allow insert queries to run.
Or allow the user to enter date in any format like dd-MM-yyyy or dd/MM/yyyy but internally convert it into the required format "dd-MM-yyyy hh:mm:ss" and store
Can someone help/guide me?
You can use Set DateFormat
Example
Used data type of date for illustration, but clearly you can use datetime
Set DateFormat DMY
Select try_convert(date,'15/08/2017') -- Returns 2017-08-15
Set DateFormat MDY
Select try_convert(date,'15/08/2017') -- Returns NULL
Set DateFormat YMD
Select try_convert(date,'15/08/2017') -- Returns NULL
You will likely run into issues if you want the user to input the date in the "dd-MM-YYYY" format since if the user inputs in the mm-dd-yyyy format, you'll get different results. "YYYMMDD" is a generic format that SQL Server will always interpret properly.
Once you get the date from the user, you can convert it using the particular format that you want. The following will convert the date to the ISO8601 format:
SELECT
GETDATE() AS UnconvertedDateTime,
CONVERT(nvarchar(30), GETDATE(), 126) AS UsingConvertTo_ISO8601 ;
GO
For more information on the specific date formats, I'd recommend checking out Microsoft's Convert Functions.

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.

SQL Server date formatting from string

We've recently migrated our database to a different server and since this I think the date format querying has changed somehow.
Previously we could use the following..
SELECT * FROM table WHERE date > 'YYYY-MM-DD'
However now we have to use..
SELECT * FROM table WHERE date > 'YYYY-DD-MM'
Can someone tell me what I need to change to get back to the previous version?
Try this one -
Query:
SET DATEFORMAT ymd
Read current settings:
DBCC USEROPTIONS
Output:
Set Option Value
-------------------------- -----------------
...
language us_english
dateformat ymd
...
You are right, the date format is different between the servers.
Lots of people fall into the trap of assuming that if you specify a date literal as 'YYYY-MM-DD', it will be interpreted as that regardless of the current date format. This is incorrect. SQL Server sees the 4 digits at the start of the string and correctly deduces that they represent the year. However, it then uses the current date format to tell which way round the month and day are. If you are in the UK, for example, this puts you in an awkward situation because you need a date format of DMY to interpret a date literal like 'DD-MM-YYYY', but a date format of MDY to interpret a date literal like 'YYYY-MM-DD'.
You have several options:
SET DATEFORMAT YMD, and don't let users enter dates any other way.
Use the ODBC date literal syntax {d'YYYY-MM-DD'}. This will be parsed correctly regardless of the current date format. CONVERT(DATE, 'YYYY-MM-DD', 120) has the same effect.
Remove all literal values from your queries and use parameters instead. This is by far the best alternative, and I strongly recommend it.
is you use different formats for the string then you can avoid this behaviour.
There are 2 iso formats that are always specific -- sql server will always parse them in the same way regardless of the server date format setting.
These are:
1) Short form : YYYYMMDD. Example '20120301' -- 1st March 2012
2) Long Form : YYYY-MM-DDTHH:MM:SS.msms'. Example '2012-03-01T12:13:00.000Z' -- 1st March 2012 at 13 minutes past 12 (PM)
In the long form the miliseconds is optional -- this is a perfectly acceptable ISO datetime '2012-03-01T12:13:00Z'
The Z at the end is time zone information. SQL Server doesn't actually require this. (though other products are a bit more exacting)
Try this for example:
DECLARE #foo DATETIME
SET DATEFORMAT DMY
-- this will be the 3rd of january in DMY
SET #foo = '2012-03-01'
SELECT 'DMY: Not ISO', #foo
SET #foo = '20120301'
SELECT 'DMY: ISO', #foo
SET DATEFORMAT MDY
-- this will be the 1st of March in MDY
SET #foo = '2012-03-01'
SELECT 'MDY: not ISO', #foo
SET #foo = '20120301'
SELECT 'MDY: ISO', #foo
When you use text to enter dates you should always try to use one of the two ISO standards. It just makes things much more deterministic.
Short format (SQL Server)
http://msdn.microsoft.com/en-US/library/ms187085(v=sql.90).aspx
ISO 8601 Format (SQL Server)
http://msdn.microsoft.com/en-us/library/ms190977(v=sql.90).aspx
It's a matter of language/culture
Set Language 'us_english'