How do I compare only the time part? [duplicate] - sql-server

This question already has an answer here:
Using DateTime?.Value.TimeOfDay in LINQ Query
(1 answer)
Closed 8 years ago.
I'm storing a time span in Sql Server as two columns of type datetime. (start and end)
So the date part of each column needs to be ignored.
Given some c# datetime instance, using an EF linq query, how can I determine whether the c# datetime's time is within the time span?
So the date part of all three values is ignored.

You can extract TimeOfDay property from DateTime that gives you the TimeSpan representing the time into the day:
DateTime dt = DateTime.Now;
dt.TimeOfDay;
Returns TimeSpan :
14:16:22.3100098

Related

How to fetch data from firestore based on date range in react js. For example: get all documents created between november 5th and november 16th [duplicate]

This question already has answers here:
How to query data between two dates range using Cloud FireStore?
(2 answers)
Firestore query by date range
(13 answers)
Firestore query date range with using 'where'
(1 answer)
Firestore query with timestamp
(1 answer)
Closed 5 months ago.
Unsure how to even approach it. But i am looking for a way to filter documents by a certain date range. The ranges i am looking to query for are: documents created today, this week, this month, and this year.
Any advice is much appreciated

How do I convert Excel Serial Date Numbers in an XML file to mm/dd/yyyy for SQL Server in an SSIS Package?

I received an XML file where the date fields are Excel Serial Date Numbers instead of mm/dd/yyyy dates like they usually are. I'm having trouble adding a data conversion to my preexisting SSIS package because the serial number is in an XML file, not an excel file.
The SSIS package cleans and loads one xml file into a SQL Server table.
Does anyone have any ideas? I'm working in Visual Studios 2015 fyi.
XML Data Snippet:
<AGREEMENT_CODE>1960-EMPR</AGREEMENT_CODE>
<AGREEMENT_NAME>1960-Legacy Employer Conversion
Default</AGREEMENT_NAME>
<AGREEMENT_TYPE>MBA</AGREEMENT_TYPE>
<FUND_TYPE>Health & Pension</FUND_TYPE>
<CONTRACT_START_DATE>21916</CONTRACT_START_DATE>
<EMPLOYER_ID>25568</EMPLOYER_ID>
<EMPLOYER_NAME>10409</EMPLOYER_NAME>
<BILLING_ENTITY_CODE>ACT III TELEVISION, L.P.</BILLING_ENTITY_CODE>
<BILLING_ENTITY_NAME>10409</BILLING_ENTITY_NAME>
<PARTICIPATION_START_DATE>ACT III TELEVISION, L.P.
</PARTICIPATION_START_DATE>
<PARTICIPATION_SIGNED_DATE>35917</PARTICIPATION_SIGNED_DATE>
The Excel Serial Date Numbers are on lines 6 and 13. They are 5 digit numbers.
The date in Excel is actually a number, representing (for all intents and purposes) the number of days since 30 December 1899. However there is one caveat below.
Therefore, you can convert the number to a date with DATEADD(day, #yourDateNum, '18991230')
The caveat is that Microsoft (and Lotus 1-2-3 before it) have a bug in the date calculation: they assume 1900 is a leap year, which it isn't. Therefore there's an extra day in the count, and I've adjusted the formula above to take this into account. The result, however, is that this formula doesn't work for dates before 1 March 1900.
Please check your formula with known values before putting in production!
The code that I have used for more than a decade now came from a defunct site
/// <summary>
/// Seriously? For the loss
/// <see cref="http://www.debugging.com/bug/19252"></see>
/// </summary>
/// <param name="excelDate">Number of days since 1900-01-01</param>
/// <returns>The converted days to date</returns>
public static DateTime ConvertXlsdtToDateTime(int excelDate)
{
DateTime dt = new DateTime(1899, 12, 31);
// adjust for 29 Feb 1900 which Excel considers a valid date
if (excelDate >= 60)
{
excelDate--;
}
return dt.AddDays(excelDate);
}
If you're going to use this in a Derived Column Task, then you need to convert the C# into the SSIS expression language. We'll use the ternary operator (boolean) ? truevalue : falsevalue to make this happen
DATEADD("Day", [CONTRACT_START_DATE] - ([CONTRACT_START_DATE] >= 60 ? 1 : 0), (DT_DATE)"1899-12-30")
Typically, I'd have two Derived Column Components in my data flow as it's the only way to debug things. In your case, I'd have the first Derived Column add 1 + Number Of Excel columns to the data flow.
Note, the assignment = I show here is short hand syntax for the values you put into Derived Column Name and the Expression columns in the Derived Task
BaseDate = (DT_DATE)"1899-12-30"
CONTRACT_START_DATE_Offset = [CONTRACT_START_DATE] >= 60 ? -1 : 0
PARTICIPATION_SIGNED_DATE_Offset = [PARTICIPATION_SIGNED_DATE] >= 60 ? -1 : 0
etc. Now I can check that I am correctly handling the offset value for the 1900 bug.
That then simplifies my first expression to
DATEADD("Day", [CONTRACT_START_DATE] - [CONTRACT_START_DATE_Offset], [BaseDate])
If you're really trying to track down where something could go wrong, I'd even look at encapsulating the math logic there Col1 - Col1_Offset into a precursor derived column just so I can put a data tap/data viewer on it and capture values.
As a minimal repro, I created a package that had an OLESRC component that adds our CONTRACT_START_DATE to the data flow
SELECT 35 AS CONTRACT_START_DATE
UNION ALL SELECT 21916
My Derived Column "OneShot" which uses the first expression adds the column "OneShot"
DER Multistatement adds the BaseDate and CONTRACT_START_DATE_Offset values from the second set of expressions
DER CSD adds ContractStartDate to the data flow using the third expression.
In the above image, you can see the results of a data viewer (and a copy of the Metadata at that point). My datatypes are as expected after using the DATEADD function - DT_DBTIMESTAMP.
If your type is showing as DT_WSTR, ensure that you are adding a new column and not attempting to replace the existing column.

Filtering table record based on time availability in SQL Server

I have one table tblAvailability in which I have two column StartTime time and EndTime time.
There I set StartTime=7 AM and EndTime=10.
Now I have filter in front end which send time range like 6 TO 10 OR 7:30 TO 10 like this.
I wrote the SQL query like below.
Where CONVERT(varchar, StartTime, 108) >= CONVERT(varchar, #startTime, 108)
AND CONVERT(varchar, EndTime, 108) <= CONVERT(varchar, #endTime, 108)
Now I would like to filter out rows based on start and end time range, means would like to get all records table whose start and end time ranges between selected time range.
As mentioned in the comments above, you are not clear whether you are using time of date or date and time. Can you please post more information.
You should be aware that date types and ranges in SQL Server can differ to a client language such as C# (although you don't mention your client language). For example, if you are using SQL Server "datetime" you can restrict the client date range in C# by using the appropriate type, e.g.
System.Data.SqlDbType.DateTime
You say you have written a query you want to use as to filter some data, which I assume you run within SQL Server.
Assume using C# as the client, an efficient way of returning data is to write a View in SQL Server and add this to an Entity Framework model. To query this data at the client, use LinqSQL which will convert your client code into SQL and runs surprisingly efficiently.
var filteredData = (from i in _db.vw_SomeData where i.StartDate >= fromDate && i.EndDate < toDate select i).ToList()
Be careful of your data endpoints (inclusive and exclusive values). If you use SQL Server datetime and you want all times within a day, then I use (date >= today and date < tomorrow) which is guaranteed to work. trying to test against the last second of the day with a "less than or equals" won't work where there is a time between the last second and midnight.
To sum up, comparing date and or time is best performed natively for those types. Only where some of the comparison data is a string should you convert one to the other. The only easily sortable and comparable date and time is yyyymmdd and HHmmss

Why does converting a blank string to a date in SQL Server result in 1900-01-01? [duplicate]

This question already has answers here:
SQL cast datetime
(3 answers)
Closed 5 years ago.
Running a simple T-SQL query of SELECT CONVERT(date, '') will render a result of 1900-01-01. It seems to me that it would be more consistent to convert a blank string to either 1753-01-01 (the minimum allowable date value) or NULL. 1900 just seems so arbitrary, but I assume this was a deliberate design choice made by the MS SQL programmers. What is the purpose of this functionality?
It is due to implicit conversion. The 0 date in sql server is 1/1/1900. Any dates earlier than that are a negative number.
SQL Server datetime calendar start point is start of day of 01 January 1900.
https://stackoverflow.com/a/17071583/7974050

remove time from getdate() using SQL [duplicate]

This question already has answers here:
Best approach to remove time part of datetime in SQL Server
(23 answers)
Closed 5 years ago.
I was wondering if anyone new how to remove the time hh,mm,ss from the getdate? I am very new to using SQL and am having trouble. Right now I have the date added so it could always pull the current date and add one day to that. Now I need to remove the time from being shown completely. I do NOT want to change time to 00:00:00, I want it to be completely hidden.
Here is my code:
Select DATEADD(DAY, 1, GETDATE())
Use CAST or CONVERT.
Using CAST
SELECT DATEADD(DAY,1,CAST(GETDATE() as date))
Using CONVERT
SELECT DATEADD(DAY,1,CONVERT(date,GETDATE()))

Resources