Often I find that I need to display a date and/or time in a specific format. Luckily VB.NET provides many options to adjust how a date is rendered as a string.
Today, for example, I was working on a Web-based report that can be exported as an Excel file. As part of the process I wanted the Date and Time to be appended as part of the file name, but without special characters such as hyphens or colons that might not be compatible with what Windows likes in a file name. With VB.NET this is easily done in one line:
Dim strFileName As String = "ReportFile" & (DateTime.Now).ToString("yyyyMMddTHHmmss") & ".xls"
This will output the file name as: ReportFile20110824T133027.xls.
The DateTime.ToString(StringFormat) syntax is quite powerful and flexible in customizing a date display. At it’s simplest one can use the pre-configured standard format characters with the ToString function.
For example one can use dtDate.ToString(“s”) to output a date time as a single string in the format yyyy-mm-ddThh:mm:ss . I find this handy since I can separate the string on the letter ‘T’ and have the date component in my favorite logical format of year month day using a minimum of code. It is also great since it allows the dates to be sortable if they are displayed in a sortable control such as a gridview.
Alternately one can pass in the exact format pattern of the date one would like to have as a String parameter to the ToString Function. In the example case above this format pattern would be dtDate.ToString(“yyyy-mm-dd”), which would give me the date format I want without having to split the string on the letter “T” to get the date component.
For the specifics on how to manipulate dates into a specific format I like to hit the Microsoft documentation on the DateTimeFormatInfo class, which is about as comprehensive as one might desire for each version of .NET. The class overviews provide a list of the standard format characters as well as a detailed list of the custom pattern syntax.
I’m currently using a lot of .NET 4, so i visit the site at the following URL:
Since at this URL one does have to scroll a bit to get to the lists I sometimes browse to the .NET 1.1 documentation instead which can be found at:
Some other helpful articles covering this topic are: