Format a Date

Problem

You want to convert a date or time into a formatted string.

Solution

Create a DateTime instance to represent the date, and then use the overloaded ToString method that accepts a format specifier.

Discussion

There are two types of date format strings: standard and custom. Standard format strings use a preset format according to the current culture and are identified by a single letter. They might retrieve part of the DateTime information (just a time, or just a date), and they might format it in a different order or using a different short form. Here are a few common examples:

Dim Now As DateTime = DateTime.Now ' Get just the long time, using the specifier "T" Dim LongTime As String = Now.ToString("T") ' LongTime is now "3:51:24 ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.