A datetime arithmetic in MQL4 - datetime

I would like to define a datetime type variable that is a result of a simple arithmetic operation between datetime type variables.
I've defined:
datetime duration = ( TimeCurrent() - OrderOpenTime() );
datetime TmStop = StringToTime( "1970.01.01 16:00" );
but when I call it in some other arithmetic operation or generally in code like this
ExitBuy_H1 = ( duration > TmClose && ...
or this
text[3]= "Duration: " + TimeToStr( duration, TIME_MINUTES );
it doesn't work.
TmStop instead works fine.
Does anyone know why?

datetime is a simple integer, number of seconds passed since 1970.01.01 00:00. duration in your example is also in seconds, even though it is datetime formated, when you need it in minutes, divide by 60. TmClose from your example means 16*60*60 seconds and you can compare that integer with any other int of course, but what might be the reason for that?
if you hold you position more then 16 hours, then duration > TmClose is true. if you want to convert difference in seconds (duration) into time, then you will have time converted from 1970.01.01 00:00 + duration seconds.
Anyway it is not clear what is your goal in doing this calculations? if you want to make sure that you hold that particular position more then x hours, then simple bool holdMoreThanXHours = TimeCurrent()-OrderOpenTime()>x*PeriodSeconds(PERIOD_H1), and do not forget to reselect each ticket if you have several ones in open

Fact A) the code, as-is, absolutely out of any question works.
//+------------------------------------------------------------------+
//| Test_StackOverflow.mq4 |
//+------------------------------------------------------------------+
#property strict
void OnStart() {
datetime duration = ( TimeCurrent() - OrderOpenTime() );
string txt = "Duration: " + TimeToStr( duration, TIME_MINUTES );
}
//+------------------------------------------------------------------+
0 error(s), 0 warning(s), compile time: 2000 msec 1 1
Fact B) the full MCVE-context of the code, as-is, is missing.
StackOverflow requires users to post a complete MCVE-representation of the problem. This requirement was not met in the original post.
While the datetime and int data-types are mutually interchangeable, the problem does not seem to be hidden in this intrinsic "duality" of a value representation, but must be somewhere else.
The main suspects for Why? are:
variable definition was masked by another variable having the same name
variable scope-of-definition was exceeded ( asking a variable outside of it's scope )
db.Pool-operations were not preceded by OrderSelect()

Related

How to create a momentJS object with a specfic time and a specific timezone(other than the default local time zone)?

I will receive an string(with time and date) from the frontend. The string format is this "2021-08-16T23:15:00.000Z". I intend to declare a moment object with the input string, along with a specific timezone(other than the local one).
import moment from "moment";
import "moment-timezone";
// The input string I receive from the frontend.
let strTime = "2021-08-16T23:15:00.000Z";
console.log(strTime); //2021-08-16T23:15:00.000Z
let time = moment.tz(strTime, "YYYY-MM-DDTHH:mm:ss.SSSZ","America/Boise");
console.log(time); // Moment<2021-08-16T17:15:00-06:00>, undesired value
let UTCtime = moment.utc(time);
console.log(UTCtime);
As far as what I understood from this question, console.log(time) should output a moment object of time 23:15:00, but with timezone "America/Boise".
What I intend is time to have the same time i.e "23:15:00.000", with "America/Boise" as timezone.
So that when I later convert that time to UTC, I need to get the right value w.r.t the timezone "America/Boise" and not my local timezone. How can I do this.
I figured out a solution.
const momenttz = require("moment-timezone");
const moment = require("moment");
// The input string I receive from the frontend.
let strTime = "2021-08-16T23:15:00.000Z";
console.log(strTime); //2021-08-16T23:15:00.000Z
let time = moment.utc(strTime);
time.tz("America/Boise", true);
console.log(time.tz());
console.log(time); // Moment<2021-08-16T23:15:00-06:00>, desired value
let UTCtime = moment.utc(time);
console.log(UTCtime); // Moment<2021-08-17T05:15:00Z>
In the above code, at console.log(time),time has the value "23:15:00.000" with required timezone "America/Boise". This makes it possible for you to get the right value , when you later convert it to UTC.
This is made possible by passing an optional second parameter to .tz mutator of moment-timezone as true which changes only the timezone (and its corresponding offset), and does not affect the time value.
time.tz(timezone, true);
A sample example of using this is given in the answer code above.
You can read more about it here in the Moment Timezone Documentation

Power BI DAX: Subtracting one hour from SELECTEDVALUE datetime

I am using the following measure (and a calendar table) to determine equipment uptime for a given hour of the day based on user input from a datetime slicer:
Selected Hour =
CALCULATE (
'UptimeView'[Uptime %],
FILTER (
'UptimeView',
'UptimeView'[LocalShiftDateHour] = SELECTEDVALUE ( 'CalendarTable'[DateTime] )
)
)
This is working just fine. The problem is that I also need this same calculation performed for each of the 12 hours prior to the selected hour. When I try to use the same formula but with one hour subtracted from the SELECTEDVALUE, like so...
S-1 =
CALCULATE (
'UptimeView'[Uptime %],
FILTER (
'UptimeView',
'UptimeView'[LocalShiftDateHour]
= SELECTEDVALUE ( 'CalendarTable'[DateTime] ) - ( 1 / 24 )
)
)
... I get blank cells in my table visualization, even though I know there is data for that hour:
Why does this happen? Any time I try to perform mathematical operations on the SELECTEDVALUE datetime value, it gives me blanks. But without using operations to manipulate it and just using the selected datetime itself, it works no problem. Is it not possible to subtract an hour from a SELECTEDVALUE datetime? If not, what workaround(s) should I try? (I have also attempted using -TIME(1,0,0) instead of -1/24 but that gave me blanks as well.)
Thanks in advance!!
I think the reason is that the subtraction you are operating isn't convenient to go row by row. Would you please try rather to put it as follows, and put the MAXX() function around the calculus you did, while adding another argument, which is the name of the table in which you want the subtraction to be performed:
S-1 =
CALCULATE (
'UptimeView'[Uptime %],
FILTER (
'UptimeView',
'UptimeView'[LocalShiftDateHour]
= MAXX('Replace_with_Tablename',SELECTEDVALUE(
'CalendarTable'[DateTime] ) - ( 1 / 24 ))
)
)
This is the trick I use. In fact, MAXX(tablename, expression) Evaluates an expression for each row of a table and returns the largest value.
Don't worry about the max, it doesn't have any effect on the result, since the max(one precise value in a precise row)= that same value

EntityFunction.TruncateTime not working in my query

I am using Linq to entityframework to query some infomration. I am trying to use entityfunction.truncatetime and it doesnt seem to work as expected. here is my sample query
From d In Request
Where d.Requestor= "XXXX" And d.ProcessedFlag = "N"
Select d.RequestID, RequestReason = d.RequestReason.ItemValue, RequestType = d.RequestType.ItemValue, RequestedDate = EntityFunctions.TruncateTime(d.RequestedMoveDate)
The requesteddate doesnt seem to truncate the time part and I am still getting the both Date and time.
Am I missing something here?
In .NET, the DateTime class actually represents both a date and a time. Internally, this is stored as a numeric value represented by the number of 100-nanosecond "ticks" since Midnight, January 1, 1001 AD. This number gets "converted" when it's displayed (either in output or in a debugger). This conversion is done via a format string.
Even if you truncate a DateTime's time portion, it still has a time... it's just 00:00:00, and if you don't want to see that time, you need to adjust your format string to not convert that.
Thus, if you do something like this: DateTime.Now.Date it will display `10/15/2012 00:00:00" if you use the default date conversion string (or whatever is the default format for your culture).
If you want to only display the Date portion, then you must do something like myDate.ToShortDateString() or myDate.ToString("d").
EntityFunctions is a set of tools designed to be used in Linq to Entities queries, because doing DateTime formatting is not normally allowed in a query.
For example, this code does not work:
var q = from x in dc where x.BirthDate == DateTime.Now.AddYears(-15).Date select x;
You have to do it like this:
var q = from x in dc
where x.Birthdate == EntityFunctions.TruncateTime(DateTime.Now.AddYears(-15))
select x;
This will then generate the correct SQL to do date comparisons in SQL code. This is what the EntityFunctions are designed for, not truncating dates in the select portion (although it does work). But, even though the date is truncated, it will still have a Time component, it will just be 00:00:00, and you must use a date format string to present it to your users in the manner you intend.
cant you use ToShortDateString() like below?
List<DateTime> time = new List<DateTime>();
time.Add(DateTime.Now);
var WhatDate = from date in time
select new { Date = date.ToShortDateString() };
In your case try this
From d In Request
Where d.Requestor= "XXXX" And d.ProcessedFlag = "N"
Select new{ RequestID = d.RequestID, RequestReason = d.RequestReason.ItemValue, RequestType = d.RequestType.ItemValue, RequestedDate = d.RequestedMoveDate.ToShortDateString()};

Is there a better way to encode a (MS) DateTime as an Int?

BACKGROUND (ok to ignore/skip):
I feel like there should be a better way to do what I'm doing, but I don't know what it is and I think my solution works, but I thought I'd ask in case there is something more elegant or faster or whatever.
I am developing a web page with MS Razor MVC which uses Html.DropDownList, which gives a pick list UI control which maps choices as display strings to integer ID codes. (I don't think I can have it map strings to DateTime values.)
But in a couple of cases, I want to choose from dates that are stored as DateTime objects. I realize I could make yet another table in memory that relates ID codes to DateTime values, but I thought instead (and also because I think I may want to encode dates as ints for yet another workaround of web page annoyances), I would encode the date as an int.
PROBLEM:
How best to convert the date of a DateTime object as an int value, and then later set a DateTime's date back to that date from the encoded int. The main ugliness of my solution is that DateTime provides a read-only DayOfYear function, but no way I know of to set a date back to (Date, DayOfYear), so I wrote a method with a loop, which is cute but probably slowish.
MY CURRENT (OK) SOLUTION:
public int encodeDate(DateTime date)
{
return ((date.Year - 2012) * 400) + date.DayOfYear;
}
public DateTime decodeDateCode(int dateCode)
{
int year = (dateCode / 400) + 2012;
int day = dateCode % 400;
// MS DateTime doesn't provide a direct reverse conversion for DayOfYear, so find it:
int month = 1;
int mThresh = DateTime.DaysInMonth(year, month);
while (day > mThresh)
{
day -= mThresh;
month++;
mThresh = DateTime.DaysInMonth(year, month);
}
DateTime dateValue = new DateTime(year, month, day);
return dateValue;
}
Ho about to format the timestamp as POSIX time (POSIX time / Unix time, see http://en.wikipedia.org/wiki/Unix_time)?
I had a similar problem myself and found a great solution here: Convert a Unix timestamp to a .NET DateTime
From the link:
DateTime ConvertFromUnixTimestamp(double timestamp)
{
}
double ConvertToUnixTimestamp(DateTime date)
{
}

Coldfusion calculate accountExpires

I'm trying to get all the accounts that have EXPIRED using accountExpires attribute in Active Directory.
As the attribute type is Int8 (64-bit integer) and coldfusion does not support such long integer, I am having a hard time getting this to work.
Is there a function or some sort that I can use to acheive the above?
Thanks!
A 64 bit integer in Java is a java.lang.Long. Longs are implicitly converted to Integers in ColdFusion.
accountExpires is a windows file time structure representing the number of 100-nanosecond intervals since January 1, 1601. This thread shows how we can get a windows file time to date:
long diff1601to1970 = 315532800 * 1000000000; // <-- diff in nanoseconds(1/1/1601 to 1/1/1970)
long currentFrom1970 = System.currentTimeMillis() * 1000000;
long currentFrom1601 = diff1601to1970 + currentFrom1970;
Which allows us to do the following in ColdFusion:
accountExpiresFileTime = 129407978957060010;
date = createObject("java", "java.util.Date").init(
(accountExpiresFileTime-116444736000000000)/10000
);
Hopefully that helps.

Resources