I confused why my code is not running the right output consistently, This is computation for date format. And im using military time format
Left digit character represents hours
decimal represents minutes
And last is the dateformat
Sample run with 2 digit day format dd:
Input 1 is: 3.56
Input 2 is: 21.32 03/13/2014
Output is: 1.28 03/14/2014
Sample run with 1 digit day format d. Which is my problem when the day is single digits wrong output:
Input 1 is: 3.56
Input 2 is: 21.32 03/07/2014
Output is: 1.33 03/8/2014
This is My code:
'if minutes reach 60
If Val(TextBox7.Text.Trim.Split(".")(1)) >= 60 Then
TextBox7.Text = Val(TextBox7.Text.Trim.Split(".")(0)) + 1 & "." & Val (TextBox7.Text.Trim.Split(".")(1) - 60) & " " & Format(Now, "MM/dd/yyyy")
Else
TextBox7.Text = Format(Val(TextBox6.Text) + Val(Strings.Left(time.Text.Trim, 5)), "##.00") & Strings.Right(time.Text.Trim, 11)
End If
'This is for hours convert which if the minutes reach 60
'Problem here
Dim xDate As Date = Format(CDate(Strings.Right(time.Text.Trim, 11)), "MM/dd/yyyy")
If Val(TextBox7.Text.Trim.Split(".")(0)) >= 24 Then
TextBox7.Text = Val(TextBox7.Text.Trim.Split(".")(0)) - 24 & "." & Val(TextBox7.Text.Trim.Split(".")(1)) & " " & DateAdd(DateInterval.Day, 1, xDate)
End If
You could use the .NET formats:
Console.WriteLine( date.ToString("h:mm dd/MM/yyyy"));
See on MSDN for more details about available formats
Related
I want to calculate the difference in hh:mm:ss between Now and column E. They both appear in format dd/mm/yyyy hh:mm. With the code I have written below, it only takes into consideration the hh:mm and not the days. So, if they have 2 days difference in wont add to the hours +48. The code is below:
With ws1.Range("N2:N" & lastrow1)
.Formula = "=TIME(HOUR(NOW()),MINUTE(NOW()),SECOND(NOW()))-TIME(HOUR(E2),MINUTE(E2),SECOND(32))"
End With
Just use =(NOW()-E2) and apply a custom format [hh]:mm:ss. The brackets around hh will do the trick.
If you rather need a number of hours, multiply by 24 as #Kerry Jackson suggested.
The logic behing date/time values is that 1 day = 1, so
1 hour = 1/24
1 min = 1/1440 '(that is 24*60 )
etc...
Put this in a module
Public Function DateTimeDiff(d1 As Date, d2 As Date)
Dim diff As Double
diff = ABS(d2 - d1)
DateTimeDiff = Fix(diff) & Format(diff, " hh:mm")
End Function
Then use
=DateTimeDiff( NOW(), E2 )
as the formula in the worksheet.
You might want to add some validation on the dates and return an error message if they are not valid.
Are you looking for a number which is the number of hours, or are you looking for text?
If you want the number of hours, try just subtracting the dates, and multiplying by 24, so the formula would be =(NOW()-E2)*24.
Public Function timeElapsed(ByVal target_cell As Range) As String
Dim hours As Long, minutes As Long, days As Long
If target_cell.Value = 0 Then Exit Function
x = DateDiff("n", target_cell, Now())
days = Format(Application.WorksheetFunction.RoundDown(x / 1440, 0), "00")
hours = Format(Application.WorksheetFunction.RoundDown((x - (days * 1440)) / 60, 0), "00")
minutes = Format(Application.WorksheetFunction.RoundDown((x - ((days * 1440) + (hours * 60))), 0), "00")
timeElapsed = CStr(days) & " " & "days" & " " & CStr(hours) & ":" & CStr(minutes)
End Function
And use as function with the result as below:
So you code becomes:
With ws1
.Range("N2:N" & lastrow1).FormulaR1C1 = "=timeElapsed(RC[-9])"
End With
At the begging I want tell you that I just read a lot of stack's about it and I didnt find solution so...
I'm substracting two dates
1 - 2017/05/05 17:00
2 - 2017/05/09 18:00
I want to receive "4 Days 1 Hour"
How I should do it? I tried to use DateFormat/Format/DateDiff and a lot of things.
It doesn't always have to be a ready-made VBA function. Especially with dates, I rarely find what I want exactly as VBA-ready. Try this custom function:
Function myDateDiff(ByVal d1 As Date, ByVal d2 As Date) As String
Dim days As Long, hours As Long
days = DateDiff("d", d1, d2) ' diff in days
hours = DateDiff("h", d1, d2) - days * 24 ' diff in hours
myDateDiff = days & " Day" & IIf(days > 1, "s ", " ") & hours & " Hour" & IIf(hours > 1, "s", "")
End Function
Sub Test()
Dim d1 As Date, d2 As Date
d1 = CDate("2017/05/05 17:00")
d2 = CDate("2017/05/09 18:00")
Debug.Print myDateDiff(d1, d2) ' 4 Days 1 Hour
d1 = CDate("2017/05/05 17:00")
d2 = CDate("2017/05/06 19:00")
Debug.Print myDateDiff(d1, d2) ' 1 Day 2 Hours
End Sub
This is the follow up post of this question and this question
I have created the following VBA function to calculate the seconds(also count the milliseconds) from two datetime.
Function:
Public Function ConvertDate(D1 As String, D2 As String) As Date
Dim StrD1 As Date
Dim StrD2 As Date
StrD1 = CDate(Left(D1, 10) & " " & Replace(Mid(D1, 12, 8), ".", ":"))
StrD2 = CDate(Left(D2, 10) & " " & Replace(Mid(D2, 12, 8), ".", ":"))
ConvertDate = DateDiff("s", StrD2, StrD1)
End Function
Scenario 1:
Given Dates:
2011-05-13-04.36.14.366004
2011-05-13-04.36.14.366005
Getting Result:
0
Expected Result:
0.000001
Scenario 2:
Given Dates:
2011-05-13-04.36.14.366004
2011-05-13-04.36.15.366005
Getting Result:
1
Expected Result:
1.000001
Scenario 3:
Given Dates:
2011-05-13-04.36.14.366004
2011-05-13-04.37.14.366005
Getting Result:
60
Expected Result:
60.000001
A day is 1. A date is 1 for every day past 31-Dec-1899. Today happens to be 42,556. Time is a decimal portion os a day. Today at noon will be 42,556.5 and today at 06:00 pm will be 42,556.75.
There are 24 hours in a day, 60 minutes in an hour and 60 seconds in a minute. That means that there are 86,400 seconds in a day (24 × 60 × 60) and a second is ¹⁄₈₆₄₀₀ (0.0000115740740740741) of a day. Excel's 15 digit floating point calculation sometimes fouls up (loses small amounts) time calculations due to the base-24 and base-60 numbering system.
Dim tm1 As String, tm2 As String
Dim dbl1 As Double, dbl2 As Double
Dim i As Long
With Worksheets("Sheet9")
For i = 1 To .Cells(.Rows.Count, "A").End(xlUp).Row Step 2
tm1 = .Cells(i, "A").Text
tm2 = .Cells(i + 1, "A").Text
dbl1 = CLng(CDate(Left(tm1, 10))) + _
TimeValue(Replace(Mid(tm1, 12, 8), Chr(46), Chr(58))) + _
(CDbl(Mid(tm1, 20)) / 86400)
dbl2 = CLng(CDate(Left(tm2, 10))) + _
TimeValue(Replace(Mid(tm2, 12, 8), Chr(46), Chr(58))) + _
(CDbl(Mid(tm2, 20)) / 86400)
.Cells(i + 1, "B") = (dbl2 - dbl1) * 86400
.Cells(i + 1, "B").NumberFormat = "0.000000"
Next i
End With
The above takes your time-and-date-as-text and calculates a pseudo-DateDiff to an accuracy of a millionth of a second. The results are displayed in seconds as an integer with fractions of a second as a decimal.
I need to define the shift length for 3 different types of shifts: an 8, 10, or 12 hour shift.
8 hour shift:
1st shift: 6am-2pm
2nd shift: 2pm-10pm
3rd shift: 10pm-6am
10 hour shift:
1st shift: 5am-3pm
2nd shift: 3pm-1am
12 hour shift:
1st shift: 3am-3pm
2nd shift: 3pm-3am
The problem is that I'm not sure what is the best way to deal with the midnight changeover. When you do Datediff("n", #10:00:00:pm#, #06:00:00#), it gives a negative value because it thinks you want the time difference from 6am going to 10pm (but with a negative value). This is not what I want.
My code below keeps giving me negative values for the times where it changes over the midnight line.
The extremely tricky part here is that users can submit a start_time of, let's say, 2:30:00 AM, which is past the midnight line. This further complicates things.
How can I make it so that not only does my code return the correct shift length, but also accounts for the possibility of users submitting start times after midnight?
(Switch
(Max([dbo_job.Uf_Shift_Standard])="8",
(Switch(
(tbl_OEE.shift = "SH1"),
Datediff("n", Max([start_time]), [end_time]),
(tbl_OEE.shift = "SH2"),
Datediff("n", Max([start_time]), [end_time]),
True,
Datediff("n", Max([start_time]), #23:59:59#) + Datediff("n", #00:00:00#, #06:00:00#))),
Max([dbo_job.Uf_Shift_Standard])="10",
(Switch(
(tbl_OEE.shift = "SH1"),
Datediff("n", Max([start_time]), [end_time]),
True,
Datediff("n", Max([start_time]), #23:59:59#) + Datediff("n", #00:00:00#, #01:00:00#))),
Max([dbo_job.Uf_Shift_Standard])="12",
(Switch(
(tbl_OEE.shift = "SH1"),
Datediff("n", Max([start_time]), #15:00:00#),
True,
Datediff("n", Max([start_time]), #23:59:59#) + Datediff("n", #00:00:00#, #03:00:00#)))
)
) AS actual_shift_length_minutes
You can add 1 (= one day) to the time difference, then calculate it directly using TimeValue to remove the date part:
ShiftDuration = TimeValue(CDate(#06:00:00 am# - #10:00:00 pm# + 1))
ShiftDuration = TimeValue(CDate(#10:00:00 pm# - #02:00:00 pm# + 1))
ShiftDuration = TimeValue(CDate(#02:00:00 pm# - #06:00:00 am# + 1))
All of these will return a date/time value (a timespan) of 08:00:00 which can format for display using Format as you like or convert to hours and/or minutes.
If you need to display durations of more than 24 hours, use a function like this:
Public Function FormatHourMinute( _
ByVal datTime As Date, _
Optional ByVal strSeparator As String = ":") _
As String
' Returns count of days, hours and minutes of datTime
' converted to hours and minutes as a formatted string
' with an optional choice of time separator.
'
' Example:
' datTime: #10:03# + #20:01#
' returns: 30:04
'
' 2005-02-05. Cactus Data ApS, CPH.
Dim strHour As String
Dim strMinute As String
Dim strHourMinute As String
strHour = CStr(Fix(datTime) * 24 + Hour(datTime))
' Add leading zero to minute count when needed.
strMinute = Right("0" & CStr(Minute(datTime)), 2)
strHourMinute = strHour & strSeparator & strMinute
FormatHourMinute = strHourMinute
End Function
I am working with a table similar to the following one:
PBName InputDate Amount
Michael Brown 07-jan-13 1391000,000 €
Mary Aspas 07-jan-13 -400000,000 €
Thomas Dand 15-feb-13 3000000,000 €
Mary Aspas 31-jul-13 3000000,000 €
Then, I am just trying to get the total amount by PBName when InputDate is previous to a given one:
Dim dd As Date
dd = 15-feb-13
This is the code I am using:
strSQL = "SELECT Rea.PBName, SUM(CASE WHEN Rea.InputDate < dd THEN Rea.AMOUNT / 1000000 ELSE 0 END) As NNARea "
When I try to run the query I get the message "invalid column name".
Could you please help me?
Thanks
This should work for you...
strSQL = "SELECT PBName, SUM(Amount)/1000000 AS NNARea " & _
"FROM Rea " & _
"WHERE InputDate < #" & dd & "# " & _
"GROUP BY PBName;"