SQL datetime compare - sql-server

I want to get some values from my table an there are some conditions about its datetime columns.
I want to get all hotel values of a stated city from my table, which is named "LocalHotels". Also I should declare two DateTimevalues. First value should be less than or equal to hotel's value in "start" column, which is datetime data type. Second value should be greater than or equal to hotel's value in "deadline" column, which is datetime data type, either.
All datetime values in these two columns are inserted in German CultureInfo format.
When I stated query below, there are no problems;
string query = "SELECT * FROM LocalHotels WHERE city='LONDON' AND start <='5.12.2015 00:00:00' AND deadline >='8.12.2015 00:00:00' ORDER BY city";
However when I changed day value of DateTime values from one digit to two digits, as I stated in below;
string query "SELECT * FROM LocalHotels WHERE city='LONDON' AND start <='15.12.2015 00:00:00' AND deadline >='18.12.2015 00:00:00' ORDER BY city"
I got an SQLException which indicates;
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.

Even though in Europe and everywhere in the world it makes perfect sense to use the month as the second of three items in the date. In the US and in this case, apparently, SQL's date time is MM.DD.YYYY, so you're going for the 15th month and 18th month
Therefore you should use
string query "SELECT * FROM LocalHotels WHERE city='LONDON' AND start <='12.15.2015 00:00:00' AND deadline >='12.18.2015 00:00:00' ORDER BY city"
or
string query "SELECT * FROM LocalHotels WHERE city='LONDON' AND start <='2015-12-15' AND deadline >='2015-12-18' ORDER BY city"

Try changing
15.12.2015 00:00:00
to
2015-12-15 00:00:00
and same format for the other date also.

You can view SQL Server's date and time format for yourself by running this query:
SELECT
GETDATE()
As you can see the format is YYYY-MM-DD HH:MM:SS.MMM. Stick to this and you won't run into any unexpected conversion errors.
EDIT
ISO 8601 is a standard date format. From MS Docs:
The advantage in using the ISO 8601 format is that it is an international standard with unambiguous specification. Also, this format isn't affected by the SET DATEFORMAT or SET LANGUAGE setting.
For this reason I would recommend it above all other formats. Examples:
2020-02-25
20200225
2020-02-25T18:37:00

SELECT CONVERT(char(10), GetDate(),126)
or
select convert(varchar,getDate(),112)
or
select replace(convert(varchar, getdate(), 111), '/','-')
Test out the queries above to get the date in the desired format (replace GetDate() with your date, or dateColumn).
As others pointed out you need the format YYYY-MM-DD.

Related

SQL Server date separator dot not working while inserting data

When I insert a date like this '01.03.2020 21:35:12' it changes into '2020-01-03 21:35:12.000'.
I want to insert the date with DOT as the Date separator.
NOTE: I'm not using a stored procedure, just insert query.
This is an inferior choice in format, because nobody reading that code can be certain whether you meant January 3rd or March 1st. You can get there this way, but it is ugly, unintuitive, and equally non-self-documenting:
DECLARE #d varchar(30) = '01.03.2020 21:35:12';
SELECT CONVERT(datetime, #d, 104);
Much better to use a standard, unambiguous date format for literals. These are the only two formats not subject to misinterpretation by language, dateformat, or regional settings, and therefore don't need to be accompanied by cryptic style numbers:
DECLARE #d1 varchar(30) = '20200301 21:35:12',
#d2 varchar(30) = '2020-03-01T21:35:12';
SELECT CONVERT(datetime, #d1), CONVERT(datetime, #d2);
Background:
Recommended SQL Server Date Formats
Bad Habits to Kick : Mis-handling date / range queries
Dating Responsibly
I don't think you can change the display in SSMS from the YYYY-MM-DD TIME format. If you want to change the way you get the date back when selected, you can use the CONVERT or FORMAT functions.
CONVERT function: https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/
FORMAT function: https://learn.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql
You may need to select your datetime twice with the CONVERT. Once for the date and once for the time in order to get the combination of formats you want.
-John

T SQL Conversion failed when converting date and/or time from character string from VARCHAR(MAX)

I'm using SQL Server 2014. I have a date stored as varchar(MAX) in the format of:
2019-02-18
However, I want it in the British format dd/mm/yyyy (103).
This is my SQL:
SELECT CONVERT(DATE, DateField, 103) AS "JobStartDate"
FROM tblTest
However, I keep getting this error:
Conversion failed when converting date and/or time from character string.
What am I missing?
Update: The date is initially stored as varchar max as it is coming from a 3rd party system. I have no control over this and I completly understand this is the wrong format, but this is what I have been given.
I have a date stored as varchar(MAX)
There's your problem right there.
Not only you are using the wrong data type to store dates, you are also using max which is a known performance killer.
The solution to the problem is to alter the table and store dates in a Date data type - but first, you must look up all the objects that depends on that column and make sure they will not break or change them as well.
Assuming this can't be done, or as a temporary workaround, you must first convert the data you have to Date, and then convert it back to a string representation of that date using the 103 style to get dd/mm/yyyy.
Since yyyy-mm-dd string format is not culture dependent with the date data type, you can simply do this:
SELECT CONVERT(char(10), TRY_CAST(DateField As Date), 103) As [JobStartDate]
FROM tblTest
Note I've used try_cast and not cast since the database can't stop you from storing values that can't be converted to dates in that column.
You want to format the DateField column and not convert it to date.
So first convert it to DATE and then apply the format:
SELECT FORMAT(CONVERT(DATE, DateField, 21), 'dd/MM/yyyy') AS JobStartDate
See the demo.

display current date -1 in sybase

I am trying to display the previous day's date Sybase using a select query:
select dateadd(day,-1,convert(char(10), getdate(), 23))
this query displays as 2015-06-18 00:00:00.0
I expect the output to be 2015-06-18.
How can I get that?
Try select dateadd(day,-1,convert(Date, getdate(), 365))
Try select convert(char(10),dateadd(day,-1, getdate() ), 23 )
Dateadd expects a date parameter as the third argument. In your example you're feeding it a char(10) . Even though implicit conversion from Char->DateTime is supported in Sybase, I would not code to depend on it in this case.
Well, datetime is a binary type. How it is formatted for display is up to you.
getdate() returns a datetime representing the current date/time. And dateadd() returns a datetime or date value, depending on what it started with (in your case, that would be datetime). And when you run your select statement, it's getting converted to a string using the default format configured for your Sybase instance. Hence your results.
In a nutshell, you are:
Converting the datetime value to char(10) to get an ISO 8601 format date string (yyyy-mm-dd).
Converting that back to a datetime value (so the time component is start-of-day)
Subtracting one day.
The easiest way to get what you want (yesterday's date) is this:
dateadd(day,-1, convert(date,getdate()) )
Which, when formatted for display, will come out as something like (depending on the default format configured for your Sybase instance) yyyy-mm-dd.
Or it might come out like November 29, 2015. If you want to ensure that it is an ISO 8601 date representation, you'll need to be explicit about it and cast it a char or varchar, thus:
convert(char(10) , dateadd(day,-1, convert(date,getdate()) ) , 23 )
which leaves you with a char(10) value containing yesterday's date.
If your version of Sybase doesn't support date, you'll have to fall back to what you were doing, but something like this:
convert(char(10) , dateadd(day,-1, getdate() ) , 23 )
You are telling it to give you hh:mm:ss, so that's what you are getting.
The 23 inside the convert is the format code for yyyy-mm-ddTHH:mm:ss There is no code to get yyyy-mm-dd, the closest you can get is 105 (dd-mm-yy) or 110 (mm-yy-dd).
If you need yyyy-mm-dd, then you'll have to convert the date to a string(char or varchar), and truncate the parts you don't want.
Converting Datetime

Convert One Datetime format to another in SQL Server

I have a datetime2 format in my Database 2015-06-22 06:23:42.790. I need to convert this into the following format 22/06/2015 06:23:42.790.
Is it possible?
Here is one way to do this:
DECLARE #date DATETIME2 = '2015-06-22 06:23:42.790';
SELECT cast(convert(VARCHAR(10), cast(LEFT(#date, 10) AS DATE), 3) AS VARCHAR(10))
+ ' ' + substring(cast(#date AS VARCHAR(50)), 12, 12)
Query breakdown:
First part: take first 10 characters from your datefield and then convert it to date style 3 (dd/mm/yyyy).
Second part: Add a space between date and time.
Third part: cast your datefield as varchar and extract the time which should always start in the 12th position of your string.
Join them all together and there you have it! Hope this helps!
Don't try to convert the database layout. Year Month Day is how SQL server shows the date because it ignores any international date formats.
I notice you want it as 22/06/2015 are you in the UK ? In the USA it would be 06/22/2015 Not such a problem because it's obvious that the 22 is the day. But if the date was 05/06/2015 how would sql or anyone know what day or month you're talking about.
So, get in to the habit of working in the ISO format year month day.
You don't mention what programming language. When reading data out of the database youd read it into a datetime variable. That will convert the date correctly into whatever locale your user is using. Different languages have different ways of getting the date into a datettime variable.
If it's only for display-use you can convert to varchar with FORMAT() function:
DECLARE #tab TABLE
(
datevalue DATETIME2
)
INSERT INTO #tab VALUES(GETDATE())
SELECT datevalue,
FORMAT(datevalue,'dd/MM/yyyy hh:mm:ss.fff') as newformat
FROM #tab

Correct way of specifying a given date in T-SQL

I am writing some T-SQL which needs to enforce a minimum date value onto some null fields:
DECLARE #epoch DATETIME;
set #epoch='1900-01-01';
select min = ISNULL(ValidFromDate,#epoch)
Is the string '1900-01-01' always going to return a datetime of Jan 1 1900 in any environment or will SQL server try to parse the string according to local culture rules?
If that's not good enough, what is the recommended way of specifying a particular date/time in T-SQL?
The best format for string-based dates is the ISO-8601 standard format.
For DATETIME variables and columns, this is either YYYYMMDD (for dates without time; without any dashes!) or YYYY-MM-DDTHH:MM:SS (date + time).
Contrary to popular belief, YYYY-MM-DD for DATETIME variables is NOT language-/dateformat-independent! If you try this, the second CAST will result in an error:
SET LANGUAGE us_english
SELECT CAST('2011-07-20' AS DATETIME)
SET LANGUAGE british
SELECT CAST('2011-07-20' AS DATETIME)
but this will work:
SET LANGUAGE british
SELECT CAST('20110720' AS DATETIME)
This is the best format since it's indepdendent of your language and dateformat settings in SQL Server.
For SQL Server 2008 and columns of type DATE (just date - no time), the format can also be YYYY-MM-DD (with the dashes) and that works for all settings, too.
Why there is such a difference between DATE and DATETIME is beyond me - that's just the way it is for now!
See Tibor Karaszi's excellent The Ultimate Guide to the DateTime data types for even more details and examples.

Resources