How to calculate Duration of Time between two date time through VBscript - date

How to calculate Duration of Time between two date time through VBscript
Date1 = 2021-01-22 11:43:38.000
Date2 = 2021-01-22 14:32:38.000
result should be HH:MM:SS

TimeSerial and FormatDateTime return a date or time that will take the regional settings of the computer into account. On my European computer no AM extension is shown because we use the 24h time format.
An additional problem with TimeSerial is that it will overflow once there are more than 32767 seconds.
A different approach could be to calculate the values for hours, minutes and seconds separately. A possible solution could be:
secValue = DateDiff("s",Date1,Date2)
hours = secValue \ 3600
hh = hours
if hours < 10 then
hh = Right("0" & hours, 2)
end if
mm = Right("0" & (secValue - hours * 3600) \ 60, 2)
ss = Right("0" & secValue mod 60, 2)
diff = hh & ":" & mm & ":" & ss
wscript.echo diff

Finally i answered to my Question Feeling great
Date1 = alA_Filling(0)
Date2 = alA_Filling(1)
secValue = DateDiff("s",Date1,Date2)
ts = TimeSerial(0, 0, secValue)
Duration = FormatDateTime(ts, vbLongTime)
But i got output like 2:49:00 AM why added AM to this may be this vbLongTime
how can i remove that AM

Related

Coldfusion date difference in days and hours

I'm having a problem with Coldfusion's DateDiff(). I'm trying to get the difference between two dates with times, like the following examples:
fromdate=06/11/2017 22:10
todate =16/11/2017 23:20
should return:
10 days, 1 hour and 10 minutes
fromdate=06/11/2017 22:10
todate =16/11/2017 20:20
should return:
9 days, 22 hours, 10 minutes
Any help?
Code:
<cfset dtFrom = "11/06/2017 22:10" />
<cfset dtTo = "11/16/2017 23:20" />
<cfoutput>
#DateDiff( "d", dtFrom, dtTo)# Days,
#DateDiff( "h", dtFrom, dtTo) % 24# Hours
#DateDiff( "n", dtFrom, dtTo) % 24 % 60# Minutes
</cfoutput>
In addition to the previous suggestion, DateDiff() isn't going to understand those specific strings or that "06/11/2017" should mean November 6. The result will be:
158 days 1 hours 10 minutes
For it to work as expected, you must convert the strings into date objects first. For example use LSParseDateTime with the right Locale.
fromDate = lsParseDateTime("06/11/2017 22:10", "English (UK)", "dd/MM/yyyy hh:mm");
toDate = lsParseDateTime("16/11/2017 23:20", "English (UK)", "dd/MM/yyyy hh:mm");
or possibly:
fromDate = lsParseDateTime("06/11/2017 22:10", "English (UK)");
toDate = lsParseDateTime("16/11/2017 23:20", "English (UK)");
Here is one way.
totalMinutes = datediff("n", fromDate, toDate);
days = int(totalMinutes /(24 * 60)) ;
minutesRemaining = totalMinutes - (days * 24 * 60);
hours = int(minutesRemaining / 60);
minutes = minutesRemaining mod 60;
writeoutput(days & ' days ' & hours & ' hours ' & minutes & ' minutes');

How to convert seconds into hh:mm format in Power Bi?

In Power Bi, I have a table that contains Name and TimeSpent by user in seconds.
I want to convert total seconds spent by all users into duration format (hh:mm)
When I am getting seconds in hh:mm format for each user from database query, the values are coming up like these 12:63 etc. After importing these values into power bi, I tried to set its datatype to DateTime format but power bi shows an error saying that it is not a valid value. If I set the datatype of the column as string then strings dont add up.
What can be the ideal way to do it?
you can solve this in one line:
measure = FORMAT(TIME(0;0;tableNAME[your_column]);"HH:mm:ss")
You can try the following DAX:
HHMMSS =
INT(Table[TimeSpent] / 3600) & ":" &
RIGHT("0" & INT((Table[TimeSpent] - INT(Table[TimeSpent] / 3600) * 3600) / 60), 2) & ":" &
RIGHT("0" & MOD(Table[TimeSpent], 3600), 2)
Source
Had a similar question but for D:HH:MM:SS, code below if it's of use.
DurTime (meas) =
VAR vDur = <<<duration in CALCULATE(SUM(seconds)) >>>
RETURN INT(vDur/86400) & ":" & //Days
RIGHT("0" & INT(MOD(vDur/3600,24)),2) & ":" & //Hours
RIGHT("0" & INT(MOD(vDur/60,60)),2) & ":" & //Minutes
RIGHT("0" & INT(MOD(vDur,60)),2) //Seconds
DAX code:
= TIME(0,0,SUM('Table'[Timespent]))
Then click the modelling tab and choose Format - Date Time and choose the appropriate format.
That's a better formula, which I'm using in PBI:
HHMMSS = FORMAT(TIME(int(Table[TimeSpent] / 3600); int(mod(Table[TimeSpent]; 3600) / 60);int(mod(mod(Table[TimeSpent]; 3600); 60))); "HH:mm:ss")
I wanted a Power BI Measure wich is easy to read for this problem, code below if it's of use.
HH:MM =
VAR TotalDuration = SUM(tableNAME[your_column] ) //if you use a measure just leave the SUM part out
VAR TotalHours = TRUNC (TotalDuration/3600)
VAR Min_ = FORMAT(TRUNC(TotalDuration - TotalHours * 3600),"00")
RETURN
TotalHours & ":" & Min_
The solution is adopted from the top answer of this question PowerBi Duration calculation in hh:mm:ss

display dates based on week number asp classic

I want to display the weeks dates based on a week number that I get from my db.
So if I get week=43 then it would display all 7 dates for that week.
Like this.
M=23
T=24
W=25
T=26
F=27
S=28
S=29
Have tested with a lot of date formating but I can't get it working.
So any input really appreciated, thanks!
I ended up with this, works perfect!
currentDate = Date
weekNumber=DatePart("ww", currentDate, vbMonday, vbFirstFourDays)
y = Year(Date)
Public Function FirstDayOfWeek(Year, Week)
Dim TempDate
TempDate = DateSerial(Year, 1, 1)
Do Until DatePart("ww", TempDate, vbMonday, vbFirstFourDays) = 1
TempDate = TempDate + 7
Loop
TempDate = TempDate + (7 * (Week - 1))
FirstDayOfWeek = TempDate - Weekday(TempDate, vbMonday) + 1
End Function
Dim startDatum
Dim slutDatum
startDatum = FirstDayOfWeek(y, weekNumber)
slutDatum = startDatum + 6
mon=DatePart("d", startDatum)
tus=DatePart("d", startDatum+1)
wen=DatePart("d", startDatum+2)
tur=DatePart("d", startDatum+3)
fri=DatePart("d", startDatum+4)
sat=DatePart("d", startDatum+5)
sun=DatePart("d", startDatum+6)
Well, there isn't really an inverse DatePart() function, so you have to make your own calculations.
dim w, wd, y, m, i
y = Year(Date) '- year of the week in question; I'm using today's date
w = 43
wd = DateAdd("d",w*7,CDate("1/1/" & y)) '- adjust as needed for 1st week of year
m = DateAdd("d",2-Weekday(wd),wd) '- find Monday of week
Hopefully, you can go from there.

Compare dates in Lua

I have a variable with a date table that looks like this
* table:
[day]
* number: 15
[year]
* number: 2015
[month]
* number: 2
How do I get the days between the current date and the date above? Many thanks!
You can use os.time() to convert your table to seconds and get the current time and then use os.difftime() to compute the difference. see Lua Wiki for more details.
reference = os.time{day=15, year=2015, month=2}
daysfrom = os.difftime(os.time(), reference) / (24 * 60 * 60) -- seconds in a day
wholedays = math.floor(daysfrom)
print(wholedays) -- today it prints "1"
as #barnes53 pointed out could be off by one day for a few seconds so it's not ideal, but it may be good enough for your needs.
You can use the algorithms gathered here:
chrono-Compatible Low-Level Date Algorithms
The algorithms are shown using C++, but they can be easily implemented in Lua if you like, or you can implement them in C or C++ and then just provide Lua bindings.
The basic idea using these algorithms is to compute a day number for the two dates and then just subtract them to give you the number of days.
--[[
http://howardhinnant.github.io/date_algorithms.html
Returns number of days since civil 1970-01-01. Negative values indicate
days prior to 1970-01-01.
Preconditions: y-m-d represents a date in the civil (Gregorian) calendar
m is in [1, 12]
d is in [1, last_day_of_month(y, m)]
y is "approximately" in
[numeric_limits<Int>::min()/366, numeric_limits<Int>::max()/366]
Exact range of validity is:
[civil_from_days(numeric_limits<Int>::min()),
civil_from_days(numeric_limits<Int>::max()-719468)]
]]
function days_from_civil(y, m, d)
if m <= 2 then
y = y - 1
m = m + 9
else
m = m - 3
end
local era = math.floor(y/400)
local yoe = y - era * 400 -- [0, 399]
local doy = math.modf((153*m + 2)/5) + d-1 -- [0, 365]
local doe = yoe * 365 + math.modf(yoe/4) - math.modf(yoe/100) + doy -- [0, 146096]
return era * 146097 + doe - 719468
end
local reference_date = {year=2001, month = 1, day = 1}
local date = os.date("*t")
local reference_days = days_from_civil(reference_date.year, reference_date.month, reference_date.day)
local days = days_from_civil(date.year, date.month, date.day)
print(string.format("Today is %d days into the 21st century.",days-reference_days))
os.time (under Windows, at least) is limited to years from 1970 and up. If, for example, you need a general solution to also find ages in days for people born before 1970, this won't work. You can use a julian date conversion and subtract between the two numbers (today and your target date).
A sample julian date function that will work for practically any date AD is given below (Lua v5.3 because of // but you could adapt to earlier versions):
local
function div(n,d)
local a, b = 1, 1
if n < 0 then a = -1 end
if d < 0 then b = -1 end
return a * b * (math.abs(n) // math.abs(d))
end
--------------------------------------------------------------------------------
-- Convert a YYMMDD date to Julian since 1/1/1900 (negative answer possible)
--------------------------------------------------------------------------------
function julian(year, month, day)
local temp
if (year < 0) or (month < 1) or (month > 12)
or (day < 1) or (day > 31) then
return
end
temp = div(month - 14, 12)
return (
day - 32075 +
div(1461 * (year + 4800 + temp), 4) +
div(367 * (month - 2 - temp * 12), 12) -
div(3 * div(year + 4900 + temp, 100), 4)
) - 2415021
end

Converting Epoch to Date in Matlab

I have an array of Epoch milliseconds (array of numbers) in Matlab. I would like to convert these into UTC date-time format, such as DD-MM-YYYY HH:MM.
Is there a pre-defined Matlab way to do this or will I have to write my own function?
Suppose, you start with a vector time_unix, then:
>> time_unix = 1339116554872; % example time
>> time_reference = datenum('1970', 'yyyy');
>> time_matlab = time_reference + time_unix / 8.64e7;
>> time_matlab_string = datestr(time_matlab, 'yyyymmdd HH:MM:SS.FFF')
time_matlab_string =
20120608 00:49:14.872
Notes:
1) See the definition of matlab's time.
2) 8.64e7 is number of milliseconds in a day.
3) Matlab does not apply any time-zone shifts, so the result is the same UTC time.
4) Example for backward transformation:
>> matlab_time = now;
>> unix_time = round(8.64e7 * (matlab_time - datenum('1970', 'yyyy')))
unix_time =
1339118367664
To summarize, here are two functions:
function tm = unix2matlab(tu)
tm = datenum('1970', 'yyyy') + tu / 864e5;
end
function tu = matlab2unix(tm)
tu = round(864e5 * (tm - datenum('1970', 'yyyy')));
end
The matlab time here is numeric. You can always convert it to string using datestr()
Update for nanoseconds
time_unix_nanos = 1339116554872666666;
millis = round(time_unix_nanos / 1e6);
nanos = time_unix_nanos - 1e6 * millis;
time_matlab = unix2matlab(millis);
s = [datestr(time_matlab, 'yyyymmdd HH:MM:SS.FFF'), num2str(nanos)];
s =
20120608 00:49:14.872666666
I tried the above code, but the results were wrong. I realised the main error is related to the awkward definition of the Unix time (epoch time). Unix time (epoch time) is defined as the number of seconds after 1-1-1970, 00h:00, not the number of **milli**seconds (http://en.wikipedia.org/wiki/Unix_time). With this definition, the Unix time should therefore be divided by 8.64e5 instead of 8.64e7.
In addition, datenum('1970', 'yyyy') does not seem to result in the desired reference time of 1-1-1970, 00h:00.
Here's my improved code:
tMatlab = datenum (1970,1,1,0,0) + tUnix / 86400;
Serg's answer is what I normally use, when I'm working in MATLAB. Today I found myself wanting to do the conversion to date in MATLAB as the title says - without the datestring conversion  specified in the question body - and output the date number from the shell.
Here is what I settled on for the rounded date number:
TODAY_MATLAB="$[719529 + $[`date +%s` / 24/60/60]]"
This is really just the bash equivalent of what you would expect: 719529 is the datenum of the epoch (1970-01-01 or datenum(1970,1,1) in MATLAB). I'm also fumbling through ksh lately and it seems this can be done there with:
TODAY_EPOCH=`date +%s`
TODAY_MATLAB=`expr $TODAY_EPOCH / 24 / 60 / 60 + 719529`
As a side exercise, I added the decimal portion back onto the date in bash - I didn't bother in ksh, but it's only arithmetic and goes similarly:
N_DIGITS=7
FORMAT=$(printf "%%d.%%0%dd" $N_DIGITS)
NOW_EP_SEC=`date +%s`
SEC_PER_DAY=$(( 24*60*60 ))
NOW_EP_DAY=$(( $NOW_EP /$SEC_PER_DAY ))
SEC_TODAY=$(( $NOW_EP_SEC - $NOW_EP_DAY*$SEC_PER_DAY ))
TODAY_MATLAB="$(( NOW_EP_DAY+719529 ))"
FRACTION_MATLAB="$( printf '%07d' $(( ($SEC_TODAY*10**$N_DIGITS)/SEC_PER_DAY )) )"
MATLAB_DATENUM=$( printf $FORMAT $TODAY_MATLAB $FRACTION_MATLAB )
echo $MATLAB_DATENUM