Best way to convert total minutes into HH:mm format? - vb.net

I get a return value from a web service in minutes, for example 538 minutes. I need to break this down in hours and minutes. What is the fastest way, in .net code and also VB6 code (two apps use the service) to convert this from minutes to HH:mm?
Thanks

This code should work both in .NET and VB6:
Dim hours As Integer = 538 \ 60
Dim minutes As Integer = 538 - (hours * 60)
Dim timeElapsed As String = CType(hours, String) & ":" & CType(minutes, String)
label1.Text = timeElapsed
In .NET exclusively, you should be able to do the following (which requires to be tested):
Dim timeElapsed As DateTime = New DateTime(1, 1, 1, 0, 538, 0)
label1.Text = timeElapsed.ToString("HH:mm")
I hope this helps!

In .Net you have a TimeSpan class so you can do the following
Dim t As New TimeSpan(0, 538, 0)
'Then you have the 2 properties
t.Hours
t.Minutes

In VB6 you could just use Format(538/1440.0, "hh:mm")
VB6 Date values can be treated as a number of days, and there's 1440 minutes in a day. So 538/1440 is the number of days in your period, and then you can use Format

Take modulus 60, then integer-divide by 60.
In VB, integer division uses \.

If you need to perform operations with other DateTime objects it might be useful to use a TimeSpan object instead, e.g.
Dim oTS As New TimeSpan(0, 538, 0)
MessageBox.Show(Format(oTS.Hours, "00") & ":" & Format(oTS.Minutes, "00"))
Dim startime As DateTime = Date.Now
Dim newtime As DateTime = startime + oTS
MessageBox.Show(newtime.ToString("HH:mm"))
If not then Matthew's suggestion of using Integer division '\' and modulo 'Mod' will work very well.

if you need strings then:
dt.ToString("HH:mm");
(info)

Related

Need help getting my points per hour function to work properly

I'm having difficulty getting my function to work right.
This function is supposed to estimate how many points per hour the user would get but instead it shows way too many numbers.
Dim now As DateTime = DateTime.Now
Private Function PointsPerHour(gainedpoints As String, totalpoints As String)
Dim firstvalue = gainedpoints
Dim secondvalue = firstvalue
Dim thirdvalue = totalpoints
Dim varJWG0 As String = "Points: "
Dim varJWG1 As String = thirdvalue
Dim varJWG2 As String = " Points Per Hour: "
Dim varJJM0 As Double = Double.Parse(thirdvalue.Replace(",", String.Empty)) - Double.Parse(secondvalue.Replace(",", String.Empty))
Dim timeSpan As TimeSpan = Now - DateTime.Now.ToLocalTime
Dim dbl_ As Double = varJJM0 / timeSpan.TotalHours * -1.0
Return (Convert.ToString(varJWG0 & varJWG1) & varJWG2) + dbl_.ToString("0.00")
End Function
Even if I do PointsPerHour(9, 91) it still outputs more than 1000.
What am I doing wrong?
So I am not entirely certain what it is that this method is trying to achieve in your current implementation.
Firstly the values firstValue and secondValue are the same, also firstValue does not seem to be used apart from assigning to secondValue, which just seems redundant to me.
The first problem I can see is that you have no time in this function. The timeSpan you are using to hold presumably the totalHours is not holding a useful value. you are subtracting Now from Now.ToLocalTime. You will either get 0 or your timezone offset from this equation.
Basically; assuming your 9, 91 example; you are getting ((91-9)/timeSpan) * -1).
If 9 is the points you are earning per hour, and 91 is total points, then 91/9 = hours. or if you give the hours 9 * hours = 91 (in this case 10.1).

Strange Date Parsing Results

I am trying to make a small helper app to assist in reading SCCM logs. Parsing the dates has been pretty straightforward until I get to the timezone offset. It is usually in the form of "+???". literal example: "11-01-2016 11:44:25.630+480"
DateTime.parse() handles this well most of the time. But occasionally I run into a time stamp that throws an exception. I cannot figure out why. This is where I need help. See example code below:
Dim dateA As DateTime = Nothing
Dim dateB As DateTime = Nothing
Dim dateStr_A As String = "11-07-2016 16:43:51.541+600"
Dim dateStr_B As String = "11-01-2016 11:44:25.630+480"
dateA = DateTime.Parse(dateStr_A)
dateB = DateTime.Parse(dateStr_B)
MsgBox(dateA.ToString & vbCrLf & dateB.ToString)
IF run it would seem dateStr_B is an invalid time stamp? Why is this? I've tried to figure out how to handle the +480 using the 'zzz' using .ParseExact() format as shown here Date Formatting MSDN
Am I missing something with the timezone offset? I've searched high and low but these SCCM logs seem to use a non standard way of representing the offset. Any insight would be greatly appreciated
The problem is that +480 is indeed an invalid offset. The format of the offset from UTC (as produced when using the "zzz" Custom Format Specifier) is hours and minutes. +600 is 6 hours and 0 minutes ahead of UTC, which is valid. +480 would be 4 hours and 80 minutes ahead of UTC, which is invalid as the number of minutes can't be more than 59.
If you have some external source of date and time strings that uses an offset that is simply a number of minutes (i.e. +600 means 10 hours and +480 means 8 hours), you will need to adjust the offset before using DateTime.Parse or DateTime.ParseExact.
[Edit]
The following function takes a timestamp with a positive or negative offset (of any number of digits) in minutes, and returns a DateTime. It throws an ArgumentException if the timestamp is not in a valid format.
Public Function DateTimeFromSCCM(ByVal ts As String) As DateTime
Dim pos As Integer = ts.LastIndexOfAny({"+"c, "-"c})
If pos < 0 Then Throw New ArgumentException("Timestamp must contain a timezone offset", "ts")
Dim offset As Integer
If Not Integer.TryParse(ts.Substring(pos + 1), offset) Then
Throw New ArgumentException("Timezone offset is not numeric", "ts")
End If
Dim hours As Integer = offset \ 60
Dim minutes As Integer = offset Mod 60
Dim timestamp As String = ts.Substring(0, pos + 1) & hours.ToString & minutes.ToString("00")
Dim result As DateTime
If Not DateTime.TryParse(timestamp, result) Then
Throw New ArgumentException("Invalid timestamp", "ts")
End If
Return result
End Function
Thank you for the insight. I had a feeling I would need to handle this manually. I just wanted to make sure I wasn't missing something simple in the process. My knowledge of the date and time formatting is a bit lacking.
As such, I have altered my code so that it handles the offset. Granted I will have to add some more input validation in the final product.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dateA As DateTime = Nothing
Dim dateB As DateTime = Nothing
Dim dateStr_A As String = correctOffset("11-07-2016 16:43:51.541+600")
Dim dateStr_B As String = correctOffset("11-07-2016 16:43:51.541+480")
dateA = DateTime.Parse(dateStr_A)
dateB = DateTime.Parse(dateStr_B)
MsgBox(dateA.ToString & vbCrLf & dateB.ToString)
End Sub
Public Function correctOffset(ByVal ts As String)
Dim offset As Integer = CInt(ts.Substring(ts.Length - 3))
Dim offHour As Integer = offset / 60
Dim offMin As Integer = offset - (offHour * 60)
Dim strhour As String = Nothing
Dim strmin As String = Nothing
If offHour <= 9 Then
strhour = "0" & CStr(offHour)
Else
strhour = CStr(offHour)
End If
If offMin <= 9 Then
strmin = "0" & CStr(offMin)
Else
strmin = CStr(offMin)
End If
Return ts.Substring(0, ts.Length - 3) & strhour & ":" & strmin
End Function

Subtracting Hours and Minutes from DateTime not working

I am trying to subtract hours and minutes from a DateTime variable and I have found other posts that show that you should be able to use the .AddHours(-3) in order to achieve this but it is not working for me. I am grabbing the datetime from a DateTimePicker control in vb.net. say the time is 10:00 AM, I want to subtract 3 hours from this to make it 7:00 AM. My hours variable evaluates to -3 but even when I just literally put the number -3 inside the .AddHours it still does not subtract the time. Heres the code
Dim ApptTime As DateTime = Convert.ToDateTime(DateTimePicker2.Value)
Dim travelTime As String = Label60.Text
Dim newtime As Double
Dim split() As String = travelTime.Split(" ")
If split.Length = 2 Then
Dim Minutes As String = split(0).Replace("mins", "")
Else
Dim Hours As Double = split(0).Replace("Hours", "")
Dim Minutes As Double = split(2).Replace("mins", "")
Hours = -Hours
Minutes = -Minutes
ApptTime.AddHours(Hours)
ApptTime.AddMinutes(Minutes)
Label62.Text = (ApptTime.ToString)
It's simple error ...
Dim ApptTime As DateTime = Now
'ApptTime.Subtract(New TimeSpan(1, 60, 60)) 'won't work
ApptTime = ApptTime.Subtract(New TimeSpan(1, 60, 60)) '1h , 60m , 60s
Try this:
Dim NowMinusThreeHours = DateAdd(DateInterval.Hour, -3, Now)

Converting a string to a DateTime in VB.net

I am writing an application to take SNMP data from an APC UPS and I want to do something with that data.
A few of the bits of information that I'm getting come in this format:
0d 2h 5m 45s 0ms
I want to be able to do something if that value goes under 30 minutes (total time - including the days and hours).
If I can get that string to be converted into a DateTime, then I can perform calculations on it.
I guess I'm looking to add that string to Now()... that way I can query how far in the future it is.
I hope that makes sense?
In my head the code looks something like this:
Dim timeNow As DateTime = Now
Dim snmpRuntimeRemaining As DateTime = Now + snmpDataTime
Dim runtimeRemaining As TimeSpan = snmpRuntimeRemaining - timeNow
If runtimeRemaining.TotalMinutes >= 30 Then Do Something
To add to .Now():
var t = new TimeSpan(days, hours, minutes, seconds, milliseconds);
var d = DateTime.Now + t;
Days, hours etc. you can get using a named Regex groups:
var r = new Regex(#"(?<days>\d+)d (?<hours>\d+)h...");
var m = r.Match(input);
var days = m.Groups["days"].Value;
PS You don't need to actually add to .Now, you can just do:
var t1 = (as above)
var t2 = Timespan.FromMinutes(30);
if(t1 < t2) doSth(); // if timespan from string is less (shorter) than 30 minutes
Code is in C#, but I think you can adapt it easily :)
I went a slightly different route away from Regex, and it needs tidying up - but this here is how I did it:
Dim snmpTimeDate As String = "0d 2h 5m 45s 0ms"
Dim split() As String = snmpTimeDate.Split(" ")
Dim days As String = split(0).Replace("d", "")
Dim hours As String = split(1).Replace("h", "")
Dim minutes As String = split(2).Replace("m", "")
Dim seconds As String = split(3).Replace("s", "")
Dim miliseconds As String = split(4).Replace("ms", "")
Dim snmpToTimeSpan = New TimeSpan(days, hours, minutes, seconds, miliseconds)
Dim snmpDateTime = DateTime.Now + snmpToTimeSpan
Dim runtimeRemaining As TimeSpan = snmpDateTime - DateTime.Now
If runtimeRemaining.TotalMinutes >= 30 Then Do Something
Thanks to Gerino for his help!

How to set only time part of a DateTime

I need to set datetime variable but it's time part must be 3:00:00 AM.
For example if i call getdate() now i'll get 1/20/2014 3:52:03 AM. I need to set it to 1/20/2014 3:00:00 AM.
Does anybody have a good snippet for that or any ideas how to do it right? would really appreciate some help.
The constructor for the DateTime allows you to specify hours, minutes and seconds as well as the usual day month and year.
Dim now As DateTime = DateTime.Now
Dim myDate = New DateTime(now.Year, now.Month, now.Day, 3, 0, 0, 0)
There are a lot of ways to do this - reading the documentation might give you more ideas
Dim someDate As DateTime = DateTime.Now()
Dim threeAmDate As DateTime = New DateTime(someDate.Year, _
someDate.Month, _
someDate.Day, _
3, _ 'hours
0, _ 'minutes
0, _ 'seconds
0) 'milliseconds
Console.WriteLine(threeAmDate)
try this
Label1.Text = DateAndTime.Today & " " & TimeOfDay
you can put this in a label or anything and you can change time of day to "3:00:00"
This one is old... But I came across having the same question.
Dim dt As New DateTime(_DateTo.Ticks + _TimeTo.Ticks)
--> Both '_DateTo' and/or '_TimeTo' could be Timespan or Datetime objects.