How do I convert the time to military time? - scripting

I am getting input from a file. The time maybe military or standard (AM/PM)
I need to convert the time to military.
Here are some examples of the time in the CSV file
2011-08-16, 2:28:00 PM, 15:28
2011-08-16, 1:21:00 PM, 13:28
2011-08-16, 2:13:00 PM, 16:28

Firstly I'm not sure whether I understood the question correctly.
Could be like this:
Option Explicit
Const SOURCE_PATH = "C:\source.csv"
Const DEST_PATH = "C:\destination.csv"
Dim oReg, oFso
Set oReg = New RegExp
oReg.IgnoreCase = True
oReg.Global = True
oReg.Pattern = "\b((1[0-2]|[1-9]):[0-5][0-9]:[0-5][0-9] [AP]M)\b"
Function cb_MilTime(a, b, c, d, e)
cb_MilTime = FormatDateTime(CDate(b), 4)
'cb_MilTime = Replace(cb_MilTime, ":", "") 'need seperator?
End Function
Set oFso = CreateObject("Scripting.FileSystemObject")
If oFso.FileExists(SOURCE_PATH) Then
oFso.OpenTextFile(DEST_PATH, 2, True).Write(oReg.Replace(_
oFso.OpenTextFile(SOURCE_PATH).ReadAll(), GetRef("cb_MilTime")))
Else
Err.Raise 8, "Source path does not exists"
End If
WScript.Echo "File Saved to "& DEST_PATH
Set oFso = Nothing
Set oReg = Nothing

Something like this should work:
Const militaryTimeFormat As String = "HH:mm"
' convert to a string in military time
Dim input As String = DateTime.Now.ToString(militaryTimeFormat)
' convert from a string in military time
Dim time As DateTime = DateTime.ParseExact(input, militaryTimeFormat, Nothing)

Related

Parsing numbers containing commas or periods

I have three values which need to be sorted from highest to lowest value. I use the following code which works like a charm until I want to use periods "." and commas ",". If I type "1,3" it displays as I like, but if I type "1.3" it changes to 13. My end users need to be able to use both commas and periods.
How can I fix this?
Dim IntArr(2) As Decimal
IntArr(0) = TextBox1.Text
IntArr(1) = TextBox2.Text
IntArr(2) = TextBox3.Text
Array.Sort(IntArr)
Dim highestNum As Decimal
Dim Midelnum As Decimal
Dim lowestNum As Decimal
lowestNum = IntArr(0)
Midelnum = IntArr(1)
highestNum = IntArr(2)
MsgBox("Highest " & highestNum)
MsgBox("lowest " & lowestNum)
MsgBox("middel " & Midelnum)
The problem is that it's based on culture. I say this because if I enter numbers as you described, I get the opposite effect ("1,3" -> "13", etc).
Here's a quick way to change the values to match the current culture.
At the top of your class, put this:
Imports System.Globalization
Then, you can do this:
Dim IntArr(2) As Decimal
Dim nfi As NumberFormatInfo = CultureInfo.CurrentCulture.NumberFormat
Dim sep1 As String = nfi.NumberDecimalSeparator
Dim sep2 As String = If(sep1.Equals("."), ",", ".")
Dim useComma As Boolean = (TextBox1.Text.Contains(",") Or TextBox2.Text.Contains(",") Or TextBox3.Text.Contains(","))
'Replace the separator to match the current culture for parsing
Decimal.TryParse(TextBox1.Text.Replace(sep2, sep1), IntArr(0))
Decimal.TryParse(TextBox2.Text.Replace(sep2, sep1), IntArr(1))
Decimal.TryParse(TextBox3.Text.Replace(sep2, sep1), IntArr(2))
Array.Sort(IntArr)
sep1 = If(useComma, ",", ".")
sep2 = If(useComma, ".", ",")
'Reformat the results to match the user's input
Dim lowestNum As String = IntArr(0).ToString().Replace(sep2, sep1)
Dim middleNum As String = IntArr(1).ToString().Replace(sep2, sep1)
Dim highestNum As String = IntArr(2).ToString().Replace(sep2, sep1)
Dim msg As String = "Highest: {0}" & Environment.NewLine & _
"Lowest: {1}" & Environment.NewLine & _
"Middle: {2}"
msg = String.Format(msg, highestNum, lowestNum, middleNum)
MessageBox.Show(msg)
Also, since you are using .NET, you may want to skip the VB6 way of doing things. Refer to my example to see what I've used.
You could use the hack of altering the string before saving it:
TextBox.Text.Replace(".",",")
But if you want to show the original input you could have a variable to detect the entered character:
Dim isDot As Boolean = False
Dim number As String = TextBox.Text
If number.Contains(".") Then
isDot = True
End If
And in the end replace it just for purposes of displaying
If isDot Then
number.Replace(",",".")
End If
The accepted answer uses too much unnecessary string manipulation. You can use the CultureInfo object to get what you need:
Sub Main
Dim DecArr(2) As Decimal
'Select the input culture (German in this case)
Dim inputCulture As CultureInfo = CultureInfo.GetCultureInfo("de-DE")
Dim text1 As String = "1,2"
Dim text2 As String = "5,8"
Dim text3 As String = "4,567"
'Use the input culture to parse the strings.
'Side Note: It is best practice to check the return value from TryParse
' to make sure the parsing actually succeeded.
Decimal.TryParse(text1, NumberStyles.Number, inputCulture, DecArr(0))
Decimal.TryParse(text2, NumberStyles.Number, inputCulture, DecArr(1))
Decimal.TryParse(text3, NumberStyles.Number, inputCulture, DecArr(2))
Array.Sort(DecArr)
Dim format As String = "Highest: {0}" & Environment.NewLine & _
"Lowest: {1}" & Environment.NewLine & _
"Middle: {2}"
'Select the output culture (US english in this case)
Dim ouputCulture As CultureInfo = CultureInfo.GetCultureInfo("en-US")
Dim msg As String = String.Format(ouputCulture, format, DecArr(2), DecArr(1), DecArr(0))
Console.WriteLine(msg)
End Sub
This code outputs:
Highest: 5.8
Lowest: 4.567
Middle: 1.2

Vb.net - Split String and convert to DateTime

I have 1 datagridview named IncomingMailDGV.
Sample data on Contents Column:
R-1 temperature (6.25) rose above high bound SLTCR at Warehouse-1 at 27/07/15 13:40
R-2 temperature (6.62) rose above high bound SLTCR at Store at 27/07/15 13:42
R-3 temperature (6.31) rose above high bound SLTCR at Warehouse-2 at 27/07/15 13:45
Note: Some contents has three spaces on the last part of the message.
I want to get the date and time which is placed on the last part and convert it to this format: "M/dd/yyyy HH:mm tt"
I'm using below code but its not working:
Sub FilterAlert()
Try
Dim Dbcon As New OleDbConnection(connStr)
Dbcon.Open()
For x As Integer = 0 To IncomingMailDGV.Rows.Count - 1
Dim line2 As String = IncomingMailDGV.Rows(x).Cells("Contents").Value.ToString
Dim separators() As String = {",", " ", "(", ")"}
Dim length As Integer = line2.Length
Dim alertdatetime As String
Dim alertdate_time As String
data2 = line2.Split(separators, StringSplitOptions.RemoveEmptyEntries)
alertdate_time = line2.Substring(length - 14, 14)
Dim alertstring = alertdate_time.Split(separators, StringSplitOptions.RemoveEmptyEntries)
alertdatetime = alertstring(0)
alertdatetime = DateTime.ParseExact(alertdatetime, "dd/MM/yyHH:mm", Nothing)
console.writeline (alertdatetime)
Next
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
Update: Some cells on Contents Column are empty.
If you mean that there may be more than one space between the date and the time, then you can just take the last 14 characters from the string. The following code assumes that the date and time are always preceded by " at ". It's not clear what you want to do if the string is not in the correct format, this code simply ignores invalid strings.
Note that DateTime doesn't have a format, it's just numbers. You can use DateTime.ToString to output the date and time in whatever format you want.
This code is intended to replace everything inside the For loop.
Dim line2 As String = IncomingMailDGV.Rows(x).Cells("Contents").Value.ToString
Dim pos As Integer = line2.LastIndexOf(" at ")
If pos < 0 Then Continue For
Dim alertstring() As String = line2.Substring(pos + 4).Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
If alertstring.length <> 2 Then Continue For
Dim alertdatetime As DateTime
If Not DateTime.TryParseExact(alertstring(0) & alertstring(1), "dd/MM/yyHH:mm", _
System.Globalization.CultureInfo.InvariantCulture, Nothing, alertdatetime) Then Continue For
Console.WriteLine(alertdatetime.ToString("M/dd/yyyy HH:mm tt"))

DateTime change date value and set specific value of time in VB.Net

I have value of this for example
Dim start_time As String = 12/30/1899 8:30:00 PM
Then i want to change it into
Dim final_start_time As String = 0000-00-00 20:30:00 ' i want to come up with this value
or another example is
Dim start_time As String = 12/30/1899 10:30:00 AM
to
Dim final_start_time As String = 0000-00-00 10:30:00
Based on your revised Question, here is some code. Revise it as necessary. I used es-ES as culture.. actually have no clue what culture that is... but on the dateformat MSDN page, that seems to generate the format you want...
Dim myOriginalDateTime As DateTime = Now
Dim mynewDateString As String = ""
Dim myFinalDateString As String = ""
Dim culture As New System.Globalization.CultureInfo("es-ES")
mynewDateString = myOriginalDateTime.ToString("G", culture)
Dim arrDateParts() As String = Split(mynewDateString, " ")
myFinalDateString = "0000-00-00 " & arrDateParts(1)
MsgBox(myFinalDateString)
Try this link:
http://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx
And this:
http://msdn.microsoft.com/en-us/library/vstudio/az4se3k1(v=vs.100).aspx
You use the .tostring method, and specify a format.

Letting VBA convert different date formats

I've got a VBA macro which reads Excel files and needs to process the data in there, including some dates. However, depending on the user who exported these files, the dates in those sheets might be written YYYYMMDD, MM/DD/YYYY, DD.MM.YYYY, M/D/YYYY and so on. All are only formatted as text.
So far, I've tried parsing the string and creating a new date. As I encounter more exotic dates, like M/DD/YYYY or D.MM.YY, my code gets very large and doesn't seem very elegant. I've searched, but I couldn't find any standardised way or function to detect these several date formats and convert them accordingly.
Am I missing something or is simply parsing the string the only reliable way for doing this?
Try this code - it'll convert any of the following formats: DD.MM.YYYY,DD.MM.YY,YYYYMMDD,MM/DD/YYYY,MM/DD/YY,M/D/YYYY, M/D/YY.
You can easily add additional formats, just add more conversion rules to the If...ElseIf... statement.
Option Explicit
Private mStrLastPattern As String
Private mStrSourceDate As String
Private mDatResult As Date
Public Function fctDateFromString(strDate As String) As Date
mStrSourceDate = strDate
mDatResult = 0
If TryConvert("(^\d{2})\.(\d{2})\.(\d{4})$", "$2/$1/$3") Then 'DD.MM.YYYY
ElseIf TryConvert("(^\d{2})\.(\d{2})\.(\d{2})$", "$2/$1/20$3") Then 'DD.MM.YY
ElseIf TryConvert("(^\d{4})(\d{2})\.(\d{2})$", "$2/$3/$1") Then 'YYYYMMDD
ElseIf TryConvert("(^\d{2})/(\d{2})/(\d{4})$", "$1/$2/$3") Then 'MM/DD/YYYY
ElseIf TryConvert("(^\d{2})/(\d{2})/(\d{2})$", "$1/$2/20$3") Then 'MM/DD/YY
ElseIf TryConvert("(^\d{1})/(\d{1})/(\d{4})$", "0$1/0$2/$3") Then 'M/D/YYYY
ElseIf TryConvert("(^\d{1})/(\d{1})/(\d{2})$", "0$1/0$2/20$3") Then 'M/D/YY
End If
If mDatResult = 0 Then Debug.Print "Cannot find matching format for " & strDate
fctDateFromString = mDatResult
End Function
Private Function TryConvert(strFrom As String, strTo As String) As Boolean
If RegExMatch(strFrom) Then
mDatResult = RegExConvert("$1/$2/$3")
TryConvert = (mDatResult <> 0)
End If
End Function
Private Function RegExMatch(strPattern As String) As Boolean
mStrLastPattern = strPattern
With CreateObject("VBScript.RegExp")
.Pattern = strPattern
.IgnoreCase = True
.MultiLine = False
RegExMatch = .Test(mStrSourceDate)
End With
End Function
Private Function RegExConvert(strReplacePattern As String) As Date
On Error Resume Next
With CreateObject("VBScript.RegExp")
.Pattern = mStrLastPattern
.IgnoreCase = True
.MultiLine = False
RegExConvert = CDate(.Replace(mStrSourceDate, strReplacePattern))
If Err.Number Then
Err.Clear
RegExConvert = 0
End If
End With
End Function
Note, that this code will interpret MM.DD.YYYY as DD.MM.YYYY and so on as long as the number of digits matches and the resulting date is valid.

VBA Text File Input for Reading and Writing

I'm writing in VB 2010 with a form with one button to be completely idiot. I haven't done VB in awhile and noticed 2010 has a lot of changes compare when I did it a couple of years ago.
What I need done is it to read from a file and write two new separate files while writing to original. It will read from a text file to get some contents and compare the current date.
The text content will be a serial and the next two columns will be dates.
Dim iFileName As New StreamReader("G:\SAP In and Out\test.txt", False)
Dim sFileExport As New StreamWriter(DateValue(Now)) + " SAP Export", False)
Dim sFileImport As New StreamWriter(DateAdd(DateInterval.Day, 10, DateValue(Now)) + " SAP Import", False)
Dim VTS As String 'Will be used to grab the VT serial
Dim CurrentDate As Date 'Will be used to compare to grabbed dates
Dim NextDateOut As Date 'Will be used to grab next date out value
Dim NextDateIn As Date 'Will be used to grab next date in value
'Setting a consistant value with daily'
CurrentDate = DateValue(Now)
Do While Not EOF(1)
Input(iFileName),VTS,NextDateOut,NextDateIn
If CurrentDate = NextDateOut Then
'Write to the export File
sFileExport.write(VTS)
'Write under the just read line in the open file
iFileName.write(/newline + VTS + /TAB + (DateAdd(DateInterval.Day, 20, DateValue(Now)) + /tab + (DateAdd(DateInterval.Day, 30, DateValue(Now)))
ElseIf CurrentDate = NextDateIn Then
'Write to import file
sFileImport.Write(VTS)
End If
Loop
End Sub
But my syntax is off and it's obviously not running since I'm asking for help.
Please help and thanks in advance. I've been working on this for hours and haven't had any positive results yet.
Well I think its right now, but i had to add an extra function so i could test it out.
I was receiving errors o the date format because I expect you use US date format (MM/DD/YYYY) and I use UK date format (DD/MM/YYYY).
Anyway you can strip the function out as I dont think you will need it, but I've left it in anyway so you can see whats going on its quite self explanatory and simply converts between the date formats, though it was made more difficult by the fact your days and month are not two digits long (no leading zero).
I hope it helps point you in the right direction and you can chop and change it to your preference.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim iFileName As New System.IO.StreamReader("c:\temp\vttest.txt", False)
Dim iReadData As List(Of String)
Dim Buffer As String
'Read complete file into array
iReadData = New List(Of String)
Do While Not iFileName.EndOfStream()
Try
Buffer = ""
Buffer = iFileName.ReadLine()
iReadData.Add(Buffer)
Catch ex As Exception
'error or end of file
End Try
Loop
iFileName.Close()
'Not needed
'Dim VTS As String 'This is in iLineData(0) after we split the line
'Dim NextDateOut As Date 'This is in iLineData(1) after we split the line
'Dim NextDateIn As Date 'This is in iLineData(2) after we split the line
'Process
Dim iFileUpdated As New System.IO.StreamWriter("c:\temp\vttest_copy.txt", True)
Dim sFileExport As New System.IO.StreamWriter("c:\temp\vttest" & Replace(DateValue(Now), "/", "_") & " SAP Export.txt", True)
Dim sFileImport As New System.IO.StreamWriter("c:\temp\vttest" & Replace(DateAdd(DateInterval.Day, 10, DateValue(Now)), "/", "_") + " SAP Import.txt", True)
Dim iLineData() As String
'Setting a consistant value with daily'
Dim CurrentDate As Date = DateValue(Now)
Dim RowId = 0
Do While RowId < iReadData.Count()
iLineData = Split(iReadData(RowId), " ")
iFileUpdated.WriteLine(iLineData(0) & " " & iLineData(1) & " " & iLineData(2))
If CurrentDate = FormatDate(iLineData(1), "US", "UK") Then
'Write to the export File
sFileExport.WriteLine(iLineData(0))
'Write under the just read line in the open file
iFileUpdated.WriteLine(iLineData(0) & " " & (DateAdd(DateInterval.Day, 20, DateValue(Now))) & " " & (DateAdd(DateInterval.Day, 30, DateValue(Now))))
ElseIf CurrentDate = FormatDate(iLineData(2), "US", "UK") Then
'Write to import file
sFileImport.WriteLine(iLineData(0))
End If
RowId = RowId + 1
Loop
sFileExport.Close()
sFileImport.Close()
iFileUpdated.Close()
MsgBox("Finshed")
End Sub
'This section added because my PC is set to DD/MM/YYYY (UK)
'Expect yours is set to MM/DD/YYYY (US)
Function FormatDate(ThisDate As String, ThisFormat As String, ThisTargetFormat As String) As Date
Dim X As Integer = 0
Dim Day1 As Integer = 0
Dim Month1 As Integer = 0
Dim Year1 As Integer = 0
Dim Buf As String = ""
If ThisFormat = "US" Then
For X = 1 To Len(ThisDate)
If Mid(ThisDate, X, 1) = "/" Then
If Month1 > 0 Then
Day1 = Buf
Buf = ""
Else
Month1 = Buf
Buf = ""
End If
Else
Buf = Buf & Mid(ThisDate, X, 1)
End If
Next
Year1 = Buf
Else
For X = 1 To Len(ThisDate)
If Mid(ThisDate, X, 1) = "/" Then
If Day1 > 0 Then
Month1 = Buf
Buf = ""
Else
Day1 = Buf
Buf = ""
End If
Else
Buf = Buf & Mid(ThisDate, X, 1)
End If
Next
Year1 = Buf
End If
'reformat for output
If ThisFormat = "US" Then
If ThisTargetFormat = "US" Then
'USA
FormatDate = (Format(Month1, "00") & "/" & Format(Day1, "00") & "/" & Format(Year1, "0000"))
Else
'UK
FormatDate = (Format(Day1, "00") & "/" & Format(Month1, "00") & "/" & Format(Year1, "0000"))
End If
Else
If ThisTargetFormat = "US" Then
'USA
FormatDate = (Format(Month1, "00") & "/" & Format(Day1, "00") & "/" & Format(Year1, "0000"))
Else
'UK
FormatDate = (Format(Day1, "00") & "/" & Format(Month1, "00") & "/" & Format(Year1, "0000"))
End If
End If
End Function
Additionally i changed the file names so as not to overwrite the existing files (So i could compare the two files).
Most of the problems were arising from the back slashes in the dates in the FILENAMES - making the pc look for paths like /3/12 i guess it was translating the slashes into folder delimiters so I replaced them with UNDERSCORES on the fly.
Once you have edited the code to your preference you can OVERWRITE the existing file rather than generating a _copy.txt as thats how I tested with a _copy.txt in the sample.
Update
Thanks for the feedback. Well its strange that your (generated) files are empty, because in the ones I have ONE has data the other is empty. This leads me to the assumption that your tweaks may have something to do with it?
For your reference I have posted them below.
ORIGINAL FILE [VTSTEST.TXT]
VT1000 3/26/2013 4/5/2013
VT1100 3/26/2013 4/5/2013
VT2000 3/27/2013 4/6/2013
VT2200 3/27/2013 4/6/2013
COPY OF VTSTEST.TXT (after modification)
VT1000 3/26/2013 4/5/2013
VT1100 3/26/2013 4/5/2013
VT2000 3/27/2013 4/6/2013
VT2000 16/04/2013 26/04/2013
VT2200 3/27/2013 4/6/2013
VT2200 16/04/2013 26/04/2013
Note: I expect the two longer lines are the ones inserted inbetween the existing four lines of text
VTTEST06_04_2013 SAP Import.Txt
This file was empty
VTTEST27_03_2013 SAP Export.TXT
VT2000
VT2000