Reputation: 39
I have a file I need to access that changes it's name based on the current week. So, for example, this week the file would be called "Something Something Week of September 24.xlsm" I have a block of code as follows:
Dim weekOf As Date = Date.Today
While (weekOf.DayOfWeek <> DayOfWeek.Monday)
weekOf = weekOf.AddDays(-1)
End While
If IO.File.Exists("Something Something Week of " & weekOf.ToString("m", CultureInfo.CreateSpecificCulture("en-us")) & ".xlsm") Then
Console.WriteLine(weekOf.ToString("m", CultureInfo.CreateSpecificCulture("en-us")))
GetChartFromExcelWorksheet("Something Something Week of " & weekOf.ToString("m", CultureInfo.CreateSpecificCulture("en-us")) & ".xlsm", "Materials", 1, "msDeliveries")
Else
MsgBox("ERROR! File improperly named.")
End If
On my machine, this works perfectly. weekOf.ToString("m") always returns full month and day (i.e. September 24). On the system it's running on, it seems to flip flop at random. It'll stay September 24 for a while, then all of a sudden it switches to 24 September. Causing an error, and giving me a headache.
My obvious first though was that the PC this app runs on has a date format different than my development machine. Nope, that ain't it. Both systems are setup to display the same date format.
So, I did a bit of research and added the CultureInfo.CreateSpecificCulture("en-us") flag to try and force the format. Still no joy.
Hoping someone smarter than me can tell me what I've done wrong.
Upvotes: 0
Views: 198
Reputation: 446
As mentioned in the comments, you need to be more strict to achieve a good solution. There is a good article at the Microsoft Doc Page about Date and Time Strings. The magic line is following:
Dim CustomDate = weekOf.ToString("MMMM dd yyyy")
'the output will be for example "June 10 2020".
For the date format they are several custom format specifier. MMMM
represents the full name of the month. dd
represents the day of the month as a number, yyyy
represents the year as a number… Just to name some of the specifer that are available. So your final code could look like this:
Dim weekOf As Date = Date.Today
While (weekOf.DayOfWeek <> DayOfWeek.Monday)
weekOf = weekOf.AddDays(-1)
End While
Dim CustomDate = weekOf.ToString("MMMM dd yyyy")
'Just change the pattern if you dont need the year.
If IO.File.Exists("Something Something Week of " & CustomDate & ".xlsm") Then
Console.WriteLine(CustomDate )
GetChartFromExcelWorksheet("Something Something Week of " & CustomDate & ".xlsm", "Materials", 1, "msDeliveries")
Else
MsgBox("ERROR! File improperly named.")
End If
Upvotes: 0