displaying current minute of a soccer match - asp-classic

I could not figure out the logic I would need to display a current minute of a soccer match. I have three fields in the database.
DateFirstStarted
DateSecondStarted
DateFullEnded
I should enter DateFirstStarted when the game starts and on the website. i.e. game starts at 7:05pm, on 7:25pm it should display '20 on the website. However, it should stop on the 45th minute. Then, I enter DateSecondStarted when the second half starts and should count from 46 to 90 and freeze there. Do I make sense? How can I do it? Is there a better way to do this?
Something not too complicated should do it. I will update start date of first half and start date of second half myself.
Here is how I tried it. I dont get an error but its not working. Any suggestion appreciated.
DateFirstStarted = objLiveCommentary("DateFirstStarted")
DateFirstEnded = DateAdd("n", 45, DateFirstStarted)
DateSecondStarted = objLiveCommentary("DateSecondStarted")
DateSecondEnded = DateAdd("n", 45, DateSecondStarted)
If DateFirstStarted => NOW() => DateFirstEnded Then
Response.Write "first half"
ElseIf DateSecondStarted => NOW() => DateSecondEnded Then
Response.Write "second half"
End If

Have a look at the DateDiff function?
You pass it two datetimes and it will give you the total amount of mins / seconds / hours etc between the two values.
http://www.w3schools.com/vbScript/func_datediff.asp
E.g.
If DateDiff("n",StartOfMatch,Now()) < 45 Then
FirstHalf = True
Elseif DateDiff("n",StartOfMatch,Now()) >= 45 Then
SecondHalf = True
Else
MatchEnded = True
End If
Hope this helps you?
C

Related

Delphi displays strange results for operations with negative values to TDateTime

We have a solution in Delphi that calculates a travel's duration of a given vehicle, for example, 20 minutes, 25 minutes and so on. However, sometimes we have to antecipate the travel's start time, from a specific datetime, for example 09:00 to 08:40. Then, we need to substract a negative value from a TDateTime variable (travel's start), in this case, something like "-00:20". To do this, we multiply the datetime value by -1 (for example MyDiffDateTimeVariable * -1). The output we got is very strange, sometimes we obtain the exactly opposite behavior. In other case, an operation to extract 20 minutes results in a difference of two days from the original datetime.
Here is a sample console application that simulate our situation, with the current outputs, and what we will expected:
program DateTimeSample;
uses
System.SysUtils, System.DateUtils;
var
LDate1: TDateTime;
LDate2: TDateTime;
begin
LDate1 := IncMinute(0, 20);
LDate2 := IncMinute(0, -20);
WriteLn('Date1: ' + DateTimeToStr(LDate1));
// Output = Date1: 30/12/1899 00:20:00 [OK]
WriteLn('Date2: ' + DateTimeToStr(LDate2));
// Output = Date2: 29/12/1899 23:40:00 [OK]
WriteLn('-----');
WriteLn('Date1: ' + DateTimeToStr(LDate1 * -1));
// Output = Date1: 30/12/1899 00:20:00 [Expected 29/12/1899 23:40:00]
WriteLn('Date2: ' + DateTimeToStr(LDate2 * -1));
// Output = Date2: 31/12/1899 23:40:00 [Expected 30/12/1899 00:20:00]
ReadLn;
end.
When you inspect the value casted to double, you can see:
double(LDate1) = 0.0138888888888889
double(LDate2) = -1.98611111111111
Seems like a bug to me, because with today it returns:
double(LDate1) = 43168,0138888889
double(LDate2) = 43167,9861111111
Edit: Hmm, according the documentation, it is not a bug, it is a feature :-)
When working with negative TDateTime values, computations must handle time portion separately. The fractional part reflects the fraction of a 24-hour day without regard to the sign of the TDateTime value. For example, 6:00 A.M. on December 29, 1899 is –1.25, not –1 + 0.25, which would equal –0.75. There are no TDateTime values from –1 through 0.
Karel's answer explains what's happening. Basically, TDateTime is represented as a Double, but that doesn't mean you can work with it in the same way as you normally would a Double value. It's internal structure carries particular semantics that if you don't handle them correctly, you're bound to get some peculiar behaviour.
The key mistake you're making is in taking the negative of a date-time value. This concept doesn't really make sense. Not even if you look at dates in BC, because the calendar system has changed a number of times over the years.
This is the main reason you should favour library routines that deal with the nuances of the internal structure (whatever your platform). In Delphi that means you should use the SysUtils and DateUtils routines for working with dates and times.
You seem to be trying to hold duration as a TDateTime value. You'd be much better off determining your preferred unit of measure and using Integer (perhaps Int64) or Double (if you need support for fractions of a unit). Then you can add or subtract, preferably using library routines, the duration from your start or end times.
The following code demonstrates some examples.
var
LStartTime, LEndTime: TDateTime;
LDuration_Mins: Integer;
begin
{ Init sample values for each calculation }
LStartTime := EncodeDateTime(2018, 3, 9, 8, 40, 0, 0);
LEndTime := EncodeDateTime(2018, 3, 9, 9, 0, 0, 0);
LDuration_Mins := 20;
{ Output result of each calculation }
Writeln(Format('Whole Duration: %d', [MinutesBetween(LStartTime, LEndTime)]));
Writeln(Format('Frac Duration: %.6f', [MinuteSpan(LStartTime, LEndTime)]));
Writeln(Format('Start Time: %s', [FormatDateTime('yyyy-mm-dd hh:nn:ss', IncMinute(LEndTime, -LDuration_Mins))]));
Writeln(Format('End Time: %s', [FormatDateTime('yyyy-mm-dd hh:nn:ss', IncMinute(LStartTime, LDuration_Mins))]));
end;
Additional Considerations
You said you're dealing with vehicle travel times. If you're dealing with long-haul travel you might have some other things to think about.
Daylight saving: If a vehicle starts its journey shortly before DST changes and ends after, you need to take this into account when calculating a missing value. Perhaps easiest would be to convert date-time values to UTC for the calculation. Which leads to...
Time zone changes: Again, unless your code is time-zone aware you're bound to make mistakes.
Compiler always appears to treat TDateTime as positive when doing numerical operations on it. Try this:
uses
System.SysUtils, System.DateUtils;
function InvertDate(ADateTime: TDateTime): TDateTime;
var
LMsec: Int64;
begin
LMsec := MillisecondsBetween(ADateTime, 0); //Always Positive
if ADateTime > 0 then
LMsec := 0 - LMsec;
Result := IncMillisecond(0, LMsec);
end;
var
LDate1: TDateTime;
LDate1Negative: TDateTime;
LDate2: TDateTime;
begin
try
LDate1 := IncMinute(0, 20);
LDate2 := IncMinute(0, -20);
WriteLn('Date1: ' + DateTimeToStr(LDate1));
// Output = Date1: 30/12/1899 00:20:00 [OK]
WriteLn('Date2: ' + DateTimeToStr(LDate2));
// Output = Date2: 29/12/1899 23:40:00 [OK]
WriteLn('-----');
WriteLn('Date1: ' + DateTimeToStr( InvertDate(LDate1) ));
// Output = Date1: Expected 29/12/1899 23:40:00
WriteLn('Date2: ' + DateTimeToStr( InvertDate(LDate2) ));
// Output = Date2: 30/12/1899 00:20:00
ReadLn;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.

How to restrict order open to a certain time and close it in another certain time with Interactive Brokers API

Using Interactive Brokers API, I would like to restrict order open to a certain time for example not before 09:35, I would also like to close the position at about 5 minutes before the end of the day.I tried to use an if statment with Sys.time() but I didn't work and in addition it is not elegant..How can I fix the error or use another method to full fill my need ?
Hour<-as.integer(format(Sys.time(), "%H"))
Minute<-as.integer(format(Sys.time(), "%M"))
print(lastValue)
library(IBrokers)
options("scipen"=4)
myconid = 3
twsobj = twsConnect(myconid)
Sys.sleep(2)
myorderid = as.integer(reqIds(twsobj))
print(myorderid)
Sys.sleep(2)
if(lastValue>0.5 && Hour > 16 && Minute > 35 ){
placeOrder(twsobj,Contract=twsSTK("SPY"),Order=twsOrder(myorderid ,"BUY",1,"MKT"))
print("IT WAS A BUY ORDER")
Sys.sleep(10)
placeOrder(twsobj,Contract=twsSTK("SPY"),Order=twsOrder(myorderid + 1 ,"SELL",1,"MKT"))
} else{
placeOrder(twsobj,Contract=twsSTK("SPY"),Order=twsOrder(myorderid , "SELL" , 1 , "MKT"))
print("IT WAS A SELL ORDER")
Sys.sleep(10)
placeOrder(twsobj,Contract=twsSTK("SPY"),Order=twsOrder(myorderid + 1 , "BUY" ,1, "MKT"))
}
Every broker has a facility to specify the good after time (GAT). It should be as simple as setting this field in the R interface. In the CRAN IBrokers docs it says the field
goodAfterTime Trades Good After Time: YYYYMMDD hh:mm:ss or ""
Here's the order properties API info at IB
https://www.interactivebrokers.com/en/software/api/apiguide/java/order.htm
The trade's "Good After Time," format
"YYYYMMDD hh:mm:ss (optional time zone)"
Note, MKT orders will be filled practically instantly. A LMT order may take some time.

VBScript echo every 30 seconds

The following code writes to the screen every iteration. Based on my understanding of the DateDiff documentation, it should only write every 30 seconds. What did I do wrong?
lasttime = Now
Do While Not data.eof
'looping through database records
if DateDiff(s,lasttime,Now) >= 30 Then
lasttime = Now
WScript.Echo "It's been 30 seconds..."
End if
Loop
Change this line:
if DateDiff(s,lasttime,Now) >= 30 Then
To this (note the quotes around "s")
if DateDiff("s",lasttime,Now) >= 30 Then

correct sum of hours in access

I have two columns in an access 2010 database with some calculated field:
time_from time_until calculated_field(time_until-time_from)
10:45 15:00 4:15
13:15 16:00 2:45
11:10 16:00 4:50
08:00 15:00 7:00
08:00 23:00 15:00
Now so far, it is good: calculated field did its job to tell me total hours and mins...
now, I need a sum of a calculated field....
I put in an expression builder: =Sum([time_until]-[time_from])
I guess total sum should give me 33:50... but it gives me some 9:50. why is this happening? Is there a way to fix this?
update:
when I put like this:
=Format(Sum([vrijeme_do]-[vrijeme_od])*24)
I get a decimal point number... which I suppose is correct....
for example, 25hrs and 30mins is shown as 25,5
but, how do I format this 25,5 to look like 25:30?
As #Arvo mentioned in his comment, this is a formatting problem. Your expected result for the sum of calculated_field is 33:50. However that sum is a Date/Time value, and since the number of hours is greater than 24, the day portion of the Date/Time is advanced by 1 and the remainder 9:50 is displayed as the time. Apparently your total is formatted to display only the time portion; the day portion is not displayed.
But the actual Date/Time value for the sum of calculated_field is #12/31/1899 09:50#. You can use a custom function to display that value in your desired format:
? duration_hhnn(#12/31/1899 09:50#)
33:50
This is the function:
Public Function duration_hhnn(ByVal pInput As Date) As String
Dim lngDays As Long
Dim lngMinutes As Long
Dim lngHours As Long
Dim strReturn As String
lngDays = Int(pInput)
lngHours = Hour(pInput)
lngMinutes = Minute(pInput)
lngHours = lngHours + (lngDays * 24)
strReturn = lngHours & ":" & Format(lngMinutes, "00")
duration_hhnn = strReturn
End Function
Note the function returns a string value so you can't do further date arithmetic on it directly.
Similar to the answer from #HansUp, it can be done without VBA code like so
Format(24 * Int(SUM(elapsed_time)) + Hour(SUM(elapsed_time)), "0") & ":" & Format(SUM(elapsed_time), "Nn")
I guess you are trying to show the total in a text box? the correct expression would be =SUM([calculated_field_name]).

Weird flex date issue

Flex is driving me CRAZY and I think it's some weird gotcha with how it handles leap years and none leap years. So here's my example. I have the below dateDiff method that finds the number of days or milliseconds between two dates. If I run the following three statements I get some weird issues.
dateDiff("date", new Date(2010, 0,1), new Date(2010, 0, 31));
dateDiff("date", new Date(2010, 1,1), new Date(2010, 1, 28));
dateDiff("date", new Date(2010, 2,1), new Date(2010, 2, 31));
dateDiff("date", new Date(2010, 3,1), new Date(2010, 3, 30));
If you were to look at the date comparisons above you would expect to get 30, 27, 30, 29 as the number of days between the dates. There weird part is that I get 29 when comparing March 1 to March 31. Why is that? Is it something to do with February only having 28 days? If anyone has ANY input on this that would be greatly appreciated.
public static function dateDiff( datePart:String, startDate:Date, endDate:Date ):Number
{
var _returnValue:Number = 0;
switch (datePart) {
case "milliseconds":
_returnValue = endDate.time - startDate.time;
break;
case "date":
// TODO: Need to figure out DST problem i.e. 23 hours at DST start, 25 at end.
// Math.floor causes rounding down error with DST start at dayOfYear
_returnValue = Math.floor(dateDiff("milliseconds", startDate, endDate)/(1000 * 60 * 60 * 24));
break;
}
return _returnValue;
}
This is not a leap year problem, but rather a daylight savings time problem.
To correct the code to account for DST, you need to look at the timezoneOffset of both dates to determine if the date range is spanning a DST boundary.
var adjustment:Number = ( startDate.timezoneOffset - endDate.timezoneOffset ) * 60 * 1000;
_returnValue = endDate.time - startDate.time + adjustment;
This will get the difference between the two time zones (in minutes), convert that value to milliseconds, and then apply the timezone difference to the millisecond difference to "cancel out" the DST boundary.
Naturally, when both numbers are in the same time zone, the adjustment value becomes 0 and the time values are not adjusted.
You have part of the answer in your comment: 2010-Mar-01 0:00 until 2010-Mar-31 0:00 is thirty (!) days minus one hour (because Mar 14 is DST start in 2010). Since you floor the result of your division, you get 29.
Edit: This answer is of course based on the assumption that the time property of Date takes DST into account. This would explain your problem; I didn't check it, however.

Resources