Select records having appointment date exactly after 12 hours from current datetime - asp.net

I want to select all the records from database table whose date time(AppointmentDate column) is equal to current date time + 12 hours.
so basically the records having appointment date which are exactly after 12 hours from current datetime.
how can we write this query in linq to entites?
Thanks in advance.

Pretty straight forward:
var twelveHoursFromNow = DateTime.Now.AddHours(12);
db.Records.Where(m => m.AppointmentDate == twelveHoursFromNow);
However, the equal may be a bit restrictive. As DateTime.Now could be 12:45:30am causing you to discard an appointment at 12:45:00pm. More likely than not, you're going to want a range.
db.Records.Where(m => m.AppointmentDate > rangeStartDateTime && m.AppointmentDate < rangeEndDateTime);

Related

extract date time then compare with previous datetime

I want to make sure the date time stored in database table is not more than 2 minutes than previous captured date time.
the result returned from Database table is in this format.
[[col1:2020-05-28 04:02:21.34]]
my codes
import java.text.SimpleDateFormat
//capture current date time
def date = new Date()
println date.format('yyyy-MM-dd hh:mm:ss.SS',TimeZone.getTimeZone('UTC'))
//wait 2 minutes then capture DB table date time
WebUI.delay(120)
PostgresdbQuery = /SELECT col1 FROM table1.test/
List resultsafter = CustomKeywords.'test.database.getPostgresSQLResults'(GlobalVariable.testPostgresdbConnString , GlobalVariable.testPostgresdbUsername , GlobalVariable.testPostgresdbPassword ,GlobalVariable.testPostgresdbDriver ,PostgresdbQuery )
println(resultsafter)
//assert
assert resultsafter < date, 'Execute time is within 2 minutes'
error
Reason:
groovy.lang.GroovyRuntimeException: Cannot compare java.util.ArrayList with value '[{col1=2020-05-28 04:02:21.34}]' and java.util.Date with value '5/28/20 1:49 PM'
The result is a list of maps. To make that check work, you would have to write it as:
assert resultsAfter.first().col1 < date
This will only work for the very first result and only if there is one. Assuming, you want to assert that for all elements, you can use every or loop the results and do the asserts for each row.
Yet, at this point i'd just let the DB do the work: select all items, that dont't match the criteria and make sure, no results are found.

How to get first item of collection into DQL

In my DB I have two tables Booking & Week. A Booking have one-to-many relationship with Week.
Into Week I have a "start" and a "end" both Datetime
I would like to select all bookings (edit) that start in less than 45 days but I can't find how to achive this.
Here's what I wrote:
$bookings = $doctrine->getRepository('MyBundle:Booking')
->createQueryBuilder('b')
->where('DATE_DIFF(CURRENT_DATE(), b.weeks) <= 45')
->getQuery()->getResult();
Of course this is not working because b.weeks is collection. Instead of "weeks" I need to get the first week (aka week with the lowest "start").
Can you help me to do this?
PS: I can't do a findAll and then filter because there is more than 20.000 bookings into database....
you can join the week entity when do the where on the start datetime
$booking = $doctrine->getRepository('MyBundle:Booking')
->createQueryBuilder('b')
->join('b.weeks', 'w')
->where('w.start <= :start')
->setParameter(':start', new \DateTime('+45 days'))
->orderBy('w.start', 'ASC')
->getQuery()->getResult();
that will give you the first result of a sorted query... I haven't run this to make sure it works... but it'll give you an idea.. this solves the problem of the "weeks" being a collection .. with this method you can get to the start of the week and devise a logic that'll match your application.

SQL Server Filtering by DateTime column, when TIME portion is provided sometimes

In an SSRS report, the user searches based on start date and end date.
The challenge is, as I discovered recently, he sometimes, not always, provides the time component while searching.
Currently, the filter is done like this:
if #pEndDate is null
SET #pEndDate = getdate()
SET #PEndDate = DateAdd(dd,1,#PEndDate)
SELECT ........
FROM .....
WHERE ( Createdon >= #PStartDate AND Createdon < #PEndDate)
This is fine when he searches without time (example - #PStartDate = 2/23/2015 and #PEndDate = 2/24/2015)
How should I structure the query to deal with the time portion when he provides it? (example - #PStartDate = 2/23/2015 15:00 and #PEndDate = 2/24/2015 15:00)
If this is answered elsewhere, please point me to it. Thank you.
If you just want to match the date part then there are lot options.
1) You can use the Date type for the parameter PEndDate and PStartDate to nullify the time part
2) You can use the Convert method to get only date part of the parameter while matching.CONVERT (DATE, #PEndDate) OR CONVERT(varchar,#PEndDate,103)
3) Get Date Part only from DateTime using DateTime functions
ATEADD(dd, 0,
DATEDIFF(dd, 0, #PEndDate))
4) Get Date Part only from DateTime using FLOOR and CAST functions
CAST( -- Convert the integer to DATE
FLOOR(-- Get largest Integer less than or equal to the decimal value
CAST(GETDATE() AS DECIMAL(12, 5)) -- Convert DATETIME to DECIMAL)
AS DATETIME) 'Date Part Only'
5) Get Date Part only from DateTime using DATEPART and CONVERT functions
CONVERT(VARCHAR(4),DATEPART(YEAR, #GETDATE))
+ '/'+ CONVERT(VARCHAR(2),DATEPART(MONTH, #GETDATE))
+ '/' + CONVERT(VARCHAR(2),DATEPART(DAY, #GETDATE))
'Date Part Only'
Use whichever method suits you and you find fancy.
UPDATE
As you mentioned you need to get the time part to 00:00 with date so you can try as,
SELECT CAST( convert(varchar(10),GETDATE(),112) AS DATETIME)
--This will give you 2015-02-27 00:00:00.000
SELECT DATEADD(ms,-3, DATEADD(day, DATEDIFF(day,0,GETDATE())+1,0))
--This will give you end of days time 2015-02-27 23:59:59.997
SELECT CONVERT(nvarchar,getdate(),103) + ' 12:59:59 PM'
--This will give you custom time 27/02/2015 12:59:59 PM

Returning a date with time, when passed utc_date and timezone as input

I have an Oracle table which has a date column ( say its name is start_date) that has stored date as UTC date. I have another column that stores a timezone (like 'America/Los_Angeles'). My requirement is I need to display the date column with timestamp corresponding to the timezone stored in the timezone column.
I initially wrote a function that accepts utc_date and the timezone and returns the date as below:
return utc_date + (SUBSTR (TZ_OFFSET (timezone), 1, 1) || '1')
* TO_DSINTERVAL (
'0 '
|| SUBSTR (TZ_OFFSET (timezone), 2, 5)
|| ':00');
but I realized a flaw. It calculates offset based on current time. So it now returns -00 08:00:00.000000 for Los_Angeles. But if the date stored in the utc_date was a date when daylight was enforced, the tz_offset value is not valid anymore. Can someone provide me some pointers how can I approach this problem?
I found a solution to my problem. Instead of relying on TZ_OFFSET, I decided to do the following
return cast(from_tz(cast(utc_date as timestamp),'UTC') at time zone timezone as date);
This is returning me the desired date. If anyone see a flaw let me know

How to compare Starting time and End time of a event with existing events of same time on same day?

I am using MS SQL server 2008. Here I need to compare the newly entered start time and End time of an event with the existing event timings. In the Database I need to check the new Starting time and End time values and the time Period should not match with the existing/ already booked event timings.
I need to check this condition in the Database stored procedure, if the condition is satisfied then only accept the event. Best example is Conference hall booking.
SELECT #count = COUNT (EventID) FROM TblEvent WHERE (('#STARTTIME' BETWEEN StartTime AND EndTime) or ('#ENDTIME' BETWEEN StartTime AND EndTime));
IF #count = 0
Begin
Select #count = COUNT (EventID) FROM TblEvent WHERE (('#STARTTIME' < StartTime and '#ENDTIME' > EndTime));
END
IF #count > 0
BEGIN
SELECT 'Event is Already Exists at that point of time please select another Time ' AS 'MESSAGE';
END
Else
BEGIN
//ADD QUERY TO SAVE THE THE EVENT IN DB//
SELECT 'Event is Added' AS 'MESSAGE';
END
NOTE:
#STARTTIME = USER ENTERED START TIME,
#ENDTIME =USER ENTERED END TIME
You can use 24 hour format to solve this in your logic. you have to save existing event timings in Database. whenever new event timings entered, you need to compare with existing both start & end timings with previous ones.
For Example:
Event1: x1 to y1
Event2; x2 to y2
if(x2==x1 && y2==y1)
if(x2>x1 &&x2<y1) andif(y2<y1)
...so on based on your requirement.
Answer is (StartA <= EndB) and (EndA >= StartB). Please, read these: Determine Whether Two Date Ranges Overlap
Hey Sanjeev try the following code..!
Select * From your Event
WHERE ('A' BETWEEN StartTime AND EndTime) or ('B' BETWEEN StartTime AND EndTime)
Note:
Here A and B are your Start time and End Time,
and Italics are your database values.
If I had understood correctly, this should solve the problem.
Let us take A and B are your start time. X and Y are previously in Database.
Then (A,B) does not over lap (X,Y) when X > B or Y < A this can be told as the new event must finish before the previous one or it must start after the previously available one. So query must be
...
Where NewStartTime > EndTime or NewEndTime < StartTime;

Resources