Convert Time stored as integer to datetime - vb.net

I have time stored as integer in a database
Example: 11325 means 01:13:25
i am trying to make a function to do this work
i used the following code:
Public Function GetTimeFromInt(ByVal intTime As Integer) As DateTime
Dim strTemp As String = intTime.ToString("D6")
strTemp = strTemp.Insert(4, ":").Insert(2, ":")
Dim dtResult As DateTime = Date.ParseExact(strTemp, "HH:mm:ss", New System.Globalization.CultureInfo("en-GB"), Globalization.DateTimeStyles.None)
Return dtResult
End Function
And it is working fine. But i want to now if there is a way to do this using string formatting maybe like int.ToString("nn:nn:nn")

Yes:
123456.ToString("00:00:00")
This will give 12:34:56.

Related

How to Convert Date, Time and UTC Offset to Local DateTime

I need to get a local timezone datetime from the following XML elements:
<TransactionDate>20191202</TransactionDate>
<TransactionTime>234026</TransactionTime>
<TransactionTimezone>UTC-06:00:00</TransactionTimezone>
My local UTC offset is -05:00:00. After getting TransactionDate and TransactionTime into td and tt Date variables, I can build a Datetime like this:
Dim ldDate As New Date(td.Year, td.Month, td.Day, tt.Hour, tt.Minute, tt.Second)
I could parse out the '-06' from TransactionTimeZone and determine that I need to add 1 hour to ldDate, but there must be a more elegant way. Any ideas?
I wrote a small procedure that returns a DateTime in the local TimeZone from a DateTime in an originating TimeZone:
Public Function P_ConvertToLocalDatetime(ByVal aOriginDateTime As Date,
ByVal aOriginTimeZone As String,
ByRef aLocalDateTime As Date) As Boolean
Try
Dim liHour As Integer = CInt(Strings.Mid(aOriginTimeZone, 4, 3))
Dim liMinute As Integer = CInt(Strings.Mid(aOriginTimeZone, 8, 2))
Dim liSecond As Integer = CInt(Strings.Right(aOriginTimeZone, 2))
With aOriginDateTime
Dim offset As New DateTimeOffset(.Year, .Month, .Day, .Hour, .Minute, .Second, New TimeSpan(liHour, liMinute, liSecond))
aLocalDateTime = offset.LocalDateTime
End With
Return True
Catch ex As Exception
Return False
End Try
End Function
I'm calling it with this:
Dim lLocalDateTime as Date
If Not P_ConvertToLocalDatetime(aTransactionDatetime,
aTransactionTimezone,
aLocalDateTime) Then
Throw New Exception("Unable to convert TransactionDatetime to local time")
End If
... where aTransactionTimezone is of type String with a value like "UTC-6:00:00".
If you have transactions from all the world this might help you to use as a base and working on to improve.
Private Function FromWorldTimeToMyLocalTime(noSpacesDateTimeTransaction As String, transactionZoneString As String) As Date
Dim transactionDtTime As Date = Date.ParseExact(noSpacesDateTimeTransaction, "yyyyMMddHHmmss", Globalization.CultureInfo.InvariantCulture)
Return DateAndTime.DateAdd(DateInterval.Hour, TimeZoneInfo.FindSystemTimeZoneById(transactionZoneString).BaseUtcOffset.TotalHours, transactionDtTime)
End Function
Usage (Here the example shows a transaction is done by Hawai):
‘Here is your complete string as you have in your xml tags (date + time) it’s presumed the transaction is come by Hawai
Dim myDateTimeFromTransactionTime As String = FromWorldTimeToMyLocalTime("20191202234026", "Hawaiian Standard Time").ToString
Console.WriteLine("MyTime from transaction is " & myDateTimeFromTransactionTime)
To get all timezone infos you can use this to have an idea.
Dim timeZones As ReadOnlyCollection(Of TimeZoneInfo) = TimeZoneInfo.GetSystemTimeZones()
For Each timeZoneInfo As TimeZoneInfo In timeZones
Console.WriteLine(CStr(timeZoneInfo.Id) & " " & CStr(timeZoneInfo.BaseUtcOffset.TotalHours))
Next

Formatting String to "dd/MM/yy"

I have a string which needs converting to "dd/MM/yy". I am converting it to a Date datatype and then formatting it back to a string. I was wondering if there is an easier/elegant way of doing it.
Here is an example of how I am achieving this now
Dim strValue As String = "17/08/2016"
Dim dteValue as Date = Convert.ToDateTime(strValue)
strValue = dteValue.ToString("dd/MM/yy")
What I am looking for is a way of converting without casting it to a Date datatype, is it possible?
Without casting it to Date I would suggest:
Dim strValue As String = "17/08/2016"
strValue = strValue.PadLeft(6) & strValue.PadRight(2)
It takes my computer 1 ms to process above code 10.000 times, but 22 ms to process yours.
Edit: if the date has different lengths, you could split on the forwardslash and rebuilt it:
Dim arrSplitValue() As String = Split("17/08/2016", "/")
Dim strValue As String = arrSplitValue(0) & "/" & arrSplitValue(1) & "/" & arrSplitValue(2).PadRight(2)
You could use an extension method:
public static string ToMyDateString(this string stringDate)
{
return DateTime.Parse(stringDate).ToString("dd/MM/yy");
}
And then use it like so:
string strValue = "17/08/2016".ToMyDateString();
or
string strValue = "17/08/2016";
string strValueDate = strValue.ToMyDateString();
Just realised you're in VB.NET so pretty sure it'll translate over. If I get a moment I'll try and do it in VB.NET.
VB.NET version
<System.Runtime.CompilerServices.Extension> _
Public Shared Function ToMyDateString(stringDate As String) As String
Return DateTime.Parse(stringDate).ToString("dd/MM/yy")
End Function
Warning - this has just been put through a converter, so may need to be tweaked.

speed up function to reverse string [duplicate]

This question already has answers here:
Best way to reverse a string
(51 answers)
Closed 9 years ago.
I am using this function to reverse text but I am having a little issue with speed.
for testing I have 130,000 characters text and its taking about 10 seconds. is it possible to speed it up? This questions is different than C# as its a vb.net
Function ReverseString(ByRef strString As String) As String
Dim NextChr, TempString As String, StringLength, Count As Integer, NewString As String = Nothing
TempString = strString
StringLength = Len(TempString)
Do While Count <= StringLength
Count = Count + 1
NextChr = Mid(TempString, Count, 1)
NewString = NextChr & NewString
Loop
ReverseString = NewString
End Function
Try this:
Function Reverse(ByVal value As String) As String
' Convert to char array.
Dim arr() As Char = value.ToCharArray()
' Use Array.Reverse function.
Array.Reverse(arr)
' Construct new string.
Return New String(arr)
End Function
Source: dot net perls
Maybe something along the lines of http://msdn.microsoft.com/en-us/library/e462ax87(v=vs.90).aspx?
in VB:
Dim TestString As String = "ABCDEFG"
' Returns "GFEDCBA".
Dim revString As String = StrReverse(TestString)
Function ReverseString(ByRef strString As String) As String
Dim charArray As Char() = strString.ToCharArray()
Array.Reverse(charArray )
Dim strReversed As New String(charArray )
ReverseString = strReversed
End Function
I would convert your string to a Character Array, then just call Array.Reverse.
I just tried this and it ran in: 0.862 seconds with a string that had 26,673,152 characters. Granted I'm on a pretyy fast PC but stil.
As it was said in other answers - it is better to use special function for this: StrReverse
but, if you want to have your own function, you can use this one, it should be faster:
Function ReverseString(ByRef strString As String) As String
Dim builder As New System.Text.StringBuilder(strString.Length)
Dim index As Integer = strString.Length - 1
While index >= 0
builder.Append(strString.Chars(index))
index = index - 1
End While
ReverseString = builder.ToString
End Function

VB.Net - How can i tailor my function to read the date of the new filename structure?

Afternoon,
How can I tailor the below function in VB.net to pickup the first 8 characters of the second part of the filename in the array?
Private Function GetFormattedDateFromFileName(ByVal fileName As String) As String
Dim parts() As String = fileName.Split("-")
If parts.Length = 3 Then
Dim dt As DateTime
If DateTime.TryParseExact(parts(1), "yyyyMMdd", Nothing, Globalization.DateTimeStyles.None, dt) Then
Return dt.ToString("MM/dd/yyyy")
End If
End If
Return ""
End Function
I was using this function before because the filename would be split in 3 parts so this worked perfect for me. File name looked like below before:
542656-20130402-FTO Disclosure.pdf
548872-20120501-Funds a.pdf
848581-20110215-Alpha.pdf
Problem now is that the filename structure has been changed and will now be in 2 parts like so:
542656-20130402.pdf
548872-20120501.pdf
848581-20110215 Alpha.pdf
652162-20120711 a.pdf
So how would I go about to tailor the above function to still split the filename with the “-“ but instead of trying to parse the date exactly, for it to just look at the first 8 characters of the second part (being the date) and continue on as it has been with the rest of the code?
Kindly advise.
A
If you change your split call and length check to:
Dim parts() As String = fileName.Split("-"c, "."c, " "c)
If parts.Length > 2 Then
Then the existing code should work correctly on both versions.
Edit in response to comment:
In order to make this work on files like "12764-20120124b.pdf", you'll need to just extract the substring directly:
Private Function GetFormattedDateFromFileName(ByVal fileName As String) As String
Dim parts() As String = fileName.Split("-")
If parts.Length > 1 AndAlso parts(1).Length >= 8 Then
Dim dt As DateTime
Dim dtStr = parts(1).Substring(0, 8)
If DateTime.TryParseExact(dtStr, "yyyyMMdd", Nothing, Globalization.DateTimeStyles.None, dt) Then
Return dt.ToString("MM/dd/yyyy")
End If
End If
Return ""
End Function

how to get the fix substring from dynamic string content?

I am developing VB.NET windows app. in VS 2010.
I want to get the substring
$CostCenterId|4^10
from the below string .
PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian
Rupee^$CostCenterId|4^10$LedgerId|2^3$
The position of current string ($CostCenterId|4^10) in the sequence may be change.
but it will always between the two $ sign.
I have written the below code, but confused abt what to write next ?
Public Sub GetSubstringData()
dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian
Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Dim CostIndex As Integer
CostIndex = sDiscription.IndexOf("CostCenterId")
sDiscription.Substring(CostIndex,
End Sub
Have a look into the Split function of a string. This allows you to split a string into substrings based on a specified delimiting character.
You can then do this:
Dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Debug.WriteLine("$" + sfullString.Split("$"c)(3))
Result: $CostCenterId|4^10
You will probably want to do some error checking to make sure the string actually contains the data you expect though.
However looking at the data, what you have is a string containing key-value pairs so you would be better to have a property to hold the CostCenterId and extract the data like this:
Public Property CostCenterId As String
Public Sub Decode(ByVal code As String)
For Each pair As String In code.Split("$"c)
If pair.Length > 0 AndAlso pair.Contains("|") Then
Dim key As String = pair.Split("|"c)(0)
Dim value As String = pair.Split("|"c)(1)
Select Case key
Case "CostCenterId"
Me.CostCenterId = value
End Select
End If
Next
End Sub
Then call it like this:
Decode("PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$")
Why not split() the string by $ into an array, and then look for the element which contains CostCenterId
This should work:
Dim token = "$CostCenterId"
Dim costIndexStart As Integer = sfullString.IndexOf(token)
Dim costIndexEnd As Integer = sfullString.IndexOf("$", costIndexStart + token.Length)
Dim cost As String = sfullString.Substring(costIndexStart, costIndexEnd - costIndexStart + 1)
Result: "$CostCenterId|4^10$"
If you want to omit the dollar-signs:
Substring(costIndexStart + 1, costIndexEnd - costIndexStart - 1)
Try something like this:
Dim CostIndex As Integer
CostIndex = sDiscription.IndexOf("CostCenterId")
auxNum = sDiscription.IndexOf("$"c, CostIndex) - CostIndex
sResult = sDiscription.SubString(CostIndex, auxNum)
Your string,
Dim xString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Substring process,
xString = xString.Substring(xString.IndexOf("$CostCenter"), xString.IndexOf("$", xString.IndexOf("$CostCenter") + 1) - xString.IndexOf("$CostCenter"))
Try this Code:
Dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian" _
& "Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Dim sp() As String = {"$"}
Dim ar() As String = sfullString.Split(sp, StringSplitOptions.RemoveEmptyEntries)
Array.Sort(ar)
MsgBox("$" & ar(0))