Thursday, August 26, 2021

[VB.Net][Example] vb get date before some days

Requirement:

Client want provide a filename pattern and an number about how many days before:

for example, today is 2021/08/26

0 --> cmsPhoto_20210826.xml

1 --> cmsPhoto_20210825.xml

2 --> cmsPhoto_20210824.xml

3 --> cmsPhoto_20210823.xml

4 --> cmsPhoto_20210822.xml


So I found the pattern of this filename is:

cmsPhoto_<yyyyMMdd>.xml


Code:

Dim XML_FILENAME_PATTERN = "cmsPhoto_<yyyyMMdd>.xml"

Sub Main()

    Console.WriteLine("filename: " & getXmlFilenameByDay(1))

End Sub

    

Function getXmlFilenameByDay(ByVal day As Integer) As String

    Dim filename As String = XML_FILENAME_PATTERN

    Dim openChar As String = "<"

    Dim closeChar As String = ">"

    Dim datePattern As String = filename.Substring(filename.IndexOf(openChar) + 1, filename.IndexOf(closeChar, filename.IndexOf(openChar)) - filename.IndexOf(openChar) - 1)

    Dim dateStr As String = DateTime.Now.AddDays(day*-1).ToString(datePattern)

    return XML_FILENAME_PATTERN.replace(openChar & datePattern & closeChar, dateStr)

End Function


Result :

If use 1 as arugument:

filename: cmsPhoto_20210825.xml

If use 2 as arugument:

filename: cmsPhoto_20210824.xml

If use -3 as arugument:

filename: cmsPhoto_20210829.xml


Reference:

https://stackoverflow.com/questions/25421425/print-yesterdays-date

No comments :

Post a Comment