take a string and turn it into a date - string

I am needing to take a string like 20230131 and turn it into 2023/01/31 then eventually reformat that into DD/MM/YR format. I am reading this from a txt file through stream reader and having to write it to a new file in different format using stream writer.
Using Visual Basic
Dim Start As String
Dim FileData()
FileData = myReader.ReadFiles()
Start = FileData(2)
myWriter.WriteLine("A004 " & Start)
I have tried start = Format(FileData(2), "####/##/##")
But it keeps writing only #'s instead of the actual value.

Since the string is a date, it would be easier to convert it to a DateTime type. Here is how you can parse the string into a DateTime:
Dim NewDate As DateTime = DateTime.ParseExact(Start, "yyyyMMdd")
From there, you can format the DateTime however you want. The .NET framework provides an overloaded method on the DateTime type called ToString(). The method allows you to pass in a string for the format (and culture-specific options if desired). Here is an example of that:
NewDate.ToString("yyyy/MM/dd")
Here is a link to the method's documentation on Microsoft Learn:
https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tostring?view=net-7.0
Update:
The DateTime type, as the name suggests, stores both the date and time. Because of that, you do not need to store the individual date and time portions separately. The ToString() function can represent both date and time values together. The code below is updated to show this.
If StartDate does not have a corresponding time portion, then the below code should work. If it does have a time portion, like FileData(3), you would have to add it just like the FinishTime below.
Dim FileData()
FileData = myReader.ReadFiles()
Dim StartDate As String = FileData(2)
Dim FinishDate As String = FileData(4)
Dim FinishTime As String = FileData(5)
Dim NewStartDate As DateTime = DateTime.ParseExact(StartDate, "yyyMMdd", System.Globalization.CultureInfo.CurrentCulture)
Dim NewFinishDate As DateTime = DateTime.ParseExact(FinishDate & FinishTime, "yyyMMddhhmmss", System.Globalization.CultureInfo.CurrentCulture)
myWriter.WriteLine("A004 " & NewStartDate.ToString("dd/MM/yyyy") & " " & NewFinishDate.ToString("dd/MM/yyyy hh:mm:ss"))

Related

Convert Dropdownlist String Value to Date

I want to do a date comparison to check whether is the Before Period is bigger than After Periode
So far it has been working properly until the date range is a bit tricky
For example
The value is from a dropdownlist item
Before period is 21-10-2022
After period is 04-11-2022
It will trigger the error message I set if the before period is bigger than the period after
I have a code like this
If CDate(ddlPeriodeBefore.SelectedValue) <= CDate(ddlPeriodeBefore.SelectedValue) Then
'Does the job if the the before period is smaller than after period
Else
lblInfo.Text = "Period BEFORE Must Be SMALLER Than Period AFTER."
End If
Can anyone help me? it keeps saying "conversion from string to date is not valid"
I've tried datetime.parse, parse exact, cdate, convert.todatetime but nothing works so far, or maybe I used it the wrong way
Please help, thanks in advance
Tim Schmelter's suggestion is not wrong, but I did want to provide an alternative. Create a collection of Tuple, add the dates (both formatted string and native value) to the collection, then bind the control to the list.
Here is the alternative:
Dim dates As New List(Of Tuple(Of String, DateTime))()
Dim today = DateTime.Today
For daysSubtract = 90 To 0 Step -1
Dim dateToAdd = today.AddDays(-daysSubtract)
dates.Add(New Tuple(Of String, DateTime)(dateToAdd.ToString("dd-MM-yyyy"), dateToAdd))
Next
ddlPeriodeBefore.ValueMember = "Item1"
ddlPeriodeBefore.DisplayMember = "Item2"
ddlPeriodeBefore.DataSource = dates
ddlPeriodeAfter.ValueMember = "Item1"
ddlPeriodeAfter.DisplayMember = "Item2"
ddlPeriodeAfter.DataSource = dates
Now when you go to get the selected value, you can use a simpler conversion since the stored object is already a DateTime:
Dim beforePeriod = DirectCast(ddlPeriodeBefore.SelectedValue, DateTime)
Dim afterPeriod = DirectCast(ddlPeriodeAfter.SelectedValue, DateTime)
If (beforePeriod <= afterPeriod) Then
' ...
Else
lblInfo.Text = "Period BEFORE Must Be SMALLER Than Period AFTER."
End If
The advantage to this approach is that you do not have to refactor your code if the date formatting changes.
If DateTime.Parse works depends on your curren culture because you don't pass any. For me this works fine (but for you not):
Dim selectedValue1 = "21-10-2022"
Dim selectedValue2 = "04-11-2022"
Dim beforePeriod = Date.Parse(selectedValue1)
Dim afterPeriod = Date.Parse(selectedValue2)
So either you know the correct culture that you have used when you have created this string, then you can pass this as second parameter to Date.Parse, or you use ParseExact:
Dim beforePeriod = Date.ParseExact(selectedValue1, "dd-MM-yyyy", CultureInfo.InvariantCulture)
Dim afterPeriod = Date.ParseExact(selectedValue2, "dd-MM-yyyy", CultureInfo.InvariantCulture)
The culture is relevant because they can have different date separators and the order of the day-, month- and year-tokens are different.

Excel VBA extract date from CSV txt

I'm having trouble extracting this text, exactly as it appears, from a CSV. There are similar questions posted on SO but they don't match my requirements:
I want to extract "31 January 2017" from this row:
4,'31 January 2017','Funds Received/Credits',56,,401.45,
Currently, VBA considers it "31 Jan" without the year. I've tried applying .NumberFormat to the cell (general, text, date).
SOLUTION REQUIREMENTS:
No user action required -- Interact with the file only using VBA (not using File > Import > Wizard)
Compatible with VBA Excel 2003
Extract the full text regardless of Excel or operating system date settings
Thank you for your ideas
You can use the split function, using the comma as a delimiter like this:
sResult = Split("4,'31 January 2017','Funds Received/Credits',56,,401.45, ", ",")(1)
If you dont want the single quotes, then add the replace function like this:
sResult = Replace(Split("4,'31 January 2017','Funds Received/Credits',56,,401.45, ", ",")(1), "'", "")
If you include the "Microsoft VBScript Regular Expressions 5.5" Reference, you can set up a pattern that will extract the whole date if it is found. For example:
Dim tstring As String
Dim myregexp As RegExp
Dim StrMatch As Object
tstring = 'Line from the CSV, or entire CSV as one string
Set myregexp = New RegExp
myregexp.Pattern = "\d{1,2} [A-Z]{3,9} \d{4}"
Set StrMatch = myregexp.Execute(tstring)
You get the benefit from this method that all the dates in the CSV will be pulled out at once, much faster than using a split line by line. Additionally, the dates may be accessed by using
DateStr = StrMatch.Item(index)
for the whole string line, or substrings can be set up to get specific parts of the string(Such as month, day, year).
myregexp.Pattern = "\(d{1,2}) ([A-Z]{3,9}) (\d{4})"
Set StrMatch = myregexp.Execute(tstring)
DateStr = StrMatch.Item(index1).SubMatches(index2)
It is a very powerful tool, with a simple set of symbols for development of patterns. I highly suggest you familiarize yourself with it for manipulation of large strings.

How do I search an online document for specific string and it's value?

Example, Online document: [removed link as no longer needed]
Which outputs:
Value1=1
Value2=5
The rest of this document would have random text to ignore.
I would like to search for Value1 and Value2, then output it's value [I need this to be expandable if I decide to add new information in the future]
[the output may be longer than one character, and might be text rather than a number]
Dim Value1Result as Integer = [value from online file] '1 in this case
Dim Value2Result as Integer = [value from online file] '5 in this case
Edit: Added logic to strip the version number. Very basic but as long as the format doesn't change it should work. You'll need to handle parsing to int, double, etc if you ever use "1.2" or whatever for a version.
If I understand your question correctly, you just need to download the file, store it in a local variable, and then do something with it. Comment if this is not the case and I will adjust.
I would do this by creating a WebClient, downloading the data, converting it to a string, and then operating on it. I did not add any headers - dropbox doesn't require it, but something to keep in mind for production... Small example below:
Dim bResult() As Byte
Dim sUrl As String = "https://dl.dropboxusercontent.com/s/bus2q71wsn9txuz/Test.txt?dl=0"
Using client As New WebClient
bResult = client.DownloadData(sUrl)
End Using
Dim retData As String = Encoding.UTF8.GetString(bResult)
Dim retList As List(Of String) = retData.Split(Environment.NewLine).ToList()
Dim sMin = retList(0).Split("=").Last()
Dim sNew = retList(1).Split("=").Last()

Replace String Two Different Parts

I am extracting a column of data from a range of filenames. All my filenames are strings in the form:
Temporary PSD Report 'Month' 2011.xls
I am using Replace to extract the month from each, at the moment I am doing it in two stages which works but it seems a bit clumsy. Is there a way to use some kind of AND for multiple replacements in the same string?
Dim strfilename As String
Dim mnth As String
Dim mnthshrt As String
mnth = Replace(strfilename, "Temporary PSD Report ", "")
mnthshrt = Replace(mnth, " 2011.xls", "")
I've tried using & and AND to reference both parts to be removed but it either has no effect on the original string or produces an error.
You could also split the string at each space character and take the 4th word (index starts at 0):
s = "Temporary PSD Report 'Month' 2011.xls"
mth = Split(s, " ")(3)

How do I Use a Date in an Array in GetAllEntriesByKey?

I'm trying to use the current day in GetAllEntriesByKey by passing an array. The array so far looks like this
Dim keyarray(2) As Variant
keyarray(0) = "FF Thompson ADT"
Set keyarray(1) = dateTime
I would like to say this
Set vc = view.GetAllEntriesByKey(keyarray, False)
Here is a row of what it looks like when it works. The test agent prints out csv in an email.
FF Thompson ADT,2/3/2009,11:45:02 PM,0,6,0,,00:00:04,5400,4
I can't seem to pass a current day dateTime that runs. I can set the dateTime manually in the declaration and it works. I think it's because it's trying to also pass the time but I don't know. I have tried three ways and it says invalid key value type.
Dim dateTime As New NotesDateTime("")
Call dateTime.LSLocalTime = Now
...
keyarray(1) = dateTime.Dateonly
Dim dateTime As New NotesDateTime("")
Call dateTime.SetNow
...
keyarray(1) = dateTime.Dateonly
Dim dateTime As New NotesDateTime("Today")
...
keyarray(1) = dateTime.Dateonly
I don't know if this is useful but I read about Evaluate here.
What I'm ultimately trying to do is GetFirstEntry for "FF Thompson ADT" for the most recent day entries exist. I'm also trying to do the same for the day before that. I'm trying to sum up the files processed (the number 6) for both days and errors (the null) for the most recent day using something like this. I need to tweak it so it finds the files processed and errors for entries but I haven't gotten there but should be able to do. I'm also just trying to find the most recent date with time value for the feed ie "FF Thompson ADT".
Set entry = vc.GetFirstEntry
filesprocessed = 0
Dim errors, errortotal As Integer
errors = 0
errorstotal = 0
While Not entry Is Nothing
rowval = 0
errors = 0
Forall colval In entry.ColumnValues
If rowval > 0 Then
errors = Cint(colval)
Else
rowval = Cint(colval)
End If
End Forall
filesprocessed = filesprocessed + rowval
errorstotal = errorstotal + errors
Set entry = vc.GetNextEntry(entry)
Wend
Thanks for any help or suggestions. They are greatly appreciated.
I've only used the GetAllEntriesByKey method with an array of strings. I've never tried mixing types. But assuming differing types are valid for that method, the problem might lie in the difference between datetime types in Notes. There's a core LS datetime type and then there's a NotesDateTime object. I'd bet the view considers a date column to be made up of the core datetime types, and so it fails when you pass the NotesDateTime type.
But that issue aside, my suggestion is to create a view that has the columns you want to access, and set the sort order of the first column (containing FF Thompson ADT) to asc, then set the second column with your dates to desc. You can then access the view entries in the order you want, with the most recent being first, 2nd most recent 2nd, etc.
If by some chance the GetAllEntriesByKey method returns the documents out of order (I forget if it guarantees order), I know I've done this before using the NotesViewNavigator class. There's definitely an alternate way to do it without need to call GetAllEntriesByKey with the date key.
Here's an answer I found
Dim todaysdate As New NotesDateTime("Today")
Dim dateTime As New NotesDateTime(todaysdate.DateOnly)
Dim keyarray(1) As Variant keyarray(0) = feedname
Set keyarray(1) = dateTime
Set vc = view.GetAllEntriesByKey(keyarray, False)

Resources