<< Back to VBNET
VB.NET DateTime Format
Use DateTime format patterns. Call the ToString method with a format string.DateTime format. We format dates and times with a string pattern. Conceptually this is simple. In practice, there are details we must account for if we want a functional program.
Formatting DateTime as a string is straightforward. Often we use format patterns like "HH." But methods like ToShortDateString are also useful.
Example. First we get the current time through DateTime.Now. When you execute these code examples, the current DateTime will be different on your computer.
Here: A format string beginning with MMM (for the month) is used. Look at how the pattern matches up to the output of the program.
VB.NET program that uses format string with DateTime
Module Module1
Sub Main()
' Use current time.
' ... Use a format.
' ... Write to console.
Dim time As DateTime = DateTime.Now
Dim format As String = "MMM ddd d HH:mm yyyy"
Console.WriteLine(time.ToString(format))
End Sub
End Module
Output
Feb Tue 21 13:26 2017
Description of format
MMM Three-letter month.
ddd Three-letter day of the week.
d Day of the month.
HH Two-digit hours on 24-hour scale.
mm Two-digit minutes.
yyyy Four-digit year.
Pattern. It is possible to change the pattern used in the format string in many ways. To explore this, we try to shorten the output by changing the MMM to a single M.
Note: The pattern matches up to the output of the program. The description of the formatting string is shown in tabular format.
VB.NET program that uses different format string
Module Module1
Sub Main()
' Use current time.
' ... Use a format.
' ... Write to console.
Dim time As DateTime = DateTime.Now
Dim format As String = "M d HH:mm yy"
Console.WriteLine(time.ToString(format))
End Sub
End Module
Output
5 18 16:46 10
Description of format
M One-digit month number.
d One-digit day of the month.
HH Two-digit hours on 24-hour scale.
mm Two-digit minutes.
yy Two-digit year.
One-character formats. Here we use single-character format strings. For this feature, you pass a one-character string to the ToString function.
Note: This encodes a specific formatting style. Sometimes it might be worth memorizing the ones you like the most.
However: Searching for a formatting string table on the Internet is much easier and requires less effort.
VB.NET program that uses one-character formats
Module Module1
Sub Main()
' Acquire current time and then try format strings.
Dim now As DateTime = DateTime.Now
Console.WriteLine(now.ToString("d"))
Console.WriteLine(now.ToString("D"))
Console.WriteLine(now.ToString("f"))
Console.WriteLine(now.ToString("F"))
Console.WriteLine(now.ToString("g"))
Console.WriteLine(now.ToString("G"))
Console.WriteLine(now.ToString("m"))
Console.WriteLine(now.ToString("M"))
Console.WriteLine(now.ToString("o"))
Console.WriteLine(now.ToString("O"))
Console.WriteLine(now.ToString("s"))
Console.WriteLine(now.ToString("t"))
Console.WriteLine(now.ToString("T"))
Console.WriteLine(now.ToString("u"))
Console.WriteLine(now.ToString("U"))
Console.WriteLine(now.ToString("y"))
Console.WriteLine(now.ToString("Y"))
End Sub
End Module
Output
5/18/2010
Tuesday, May 18, 2010
Tuesday, May 18, 2010 4:47 PM
Tuesday, May 18, 2010 4:47:55 PM
5/18/2010 4:47 PM
5/18/2010 4:47:55 PM
May 18
May 18
2010-05-18T16:47:55.9620000-06:00
2010-05-18T16:47:55.9620000-06:00
2010-05-18T16:47:55
4:47 PM
4:47:55 PM
2010-05-18 16:47:55Z
Tuesday, May 18, 2010 10:47:55 PM
May, 2010
May, 2010
Helper functions. These functions, available on DateTime, allow us to format strings. For rapid application development, these are ideal because they are easy to remember and guess.
Note: The methods with the word Long in them produce considerably more verbose output.
VB.NET program that uses DateTime string functions
Module Module1
Sub Main()
' Use string helper functions.
Dim now As DateTime = DateTime.Now
Console.WriteLine(now.ToLongDateString())
Console.WriteLine(now.ToLongTimeString())
Console.WriteLine(now.ToShortDateString())
Console.WriteLine(now.ToShortTimeString())
Console.WriteLine(now.ToString())
End Sub
End Module
Output
Tuesday, May 18, 2010
4:49:57 PM
5/18/2010
4:49 PM
5/18/2010 4:49:57 PM
Short day strings. The .NET Framework gives us the ability to print the representation of a day in short form. The three-letter form returns the day name and truncates it.
Here: In this example, we use a loop construct that iterates through seven days and prints out the short form string for each of them.
For Each, ForVB.NET program that prints short day strings
Module Module1
Sub Main()
' Current time.
Dim now As DateTime = DateTime.Now
' Print out all the days.
For index As Integer = 0 To 6
Console.WriteLine(now.ToString("ddd"))
now = now.AddDays(1)
Next
End Sub
End Module
Output
Tue
Wed
Thu
Fri
Sat
Sun
Mon
Long day strings. You can also print out the long day strings using the format string dddd. For more textual output, the longer day string might be preferred.
Here: In this example, we loop over seven consecutive days and print out the long day strings.
VB.NET program that prints long day strings
Module Module1
Sub Main()
Dim now As DateTime = DateTime.Now
For index As Integer = 0 To 6
Console.WriteLine(now.ToString("dddd"))
now = now.AddDays(1)
Next
End Sub
End Module
Output
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Monday
AM, PM. When you are using a 12-hour based time system, you will typically want to display AM or PM to indicate whether it is morning or evening.
Next: This example prints out AM and PM for two times that are twelve hours apart.
Question: Are you a morning person, or a night person? This program will help you figure this out.
VB.NET program that prints AM and PM
Module Module1
Sub Main()
Dim now As DateTime = DateTime.Now
For index As Integer = 0 To 1
Console.WriteLine(now.ToString("tt "))
now = now.AddHours(12)
Next
End Sub
End Module
Output
PM
AM
Year. The year part of the format string is also important. Typically, you will want a two or four digit year, but a one-digit year is also possible with a single y.
Here: Let's look at some output in an example program that tests yy and yyyy. We see two-digit and four-digit years.
VB.NET program that prints year strings
Module Module1
Sub Main()
' Use the best y patterns.
Dim now As DateTime = DateTime.Now
Console.WriteLine(now.ToString("yy"))
Console.WriteLine(now.ToString("yyyy"))
End Sub
End Module
Output
10
2010
Empty formats. When we use a Nothing, empty, or missing format string, the default ToString implementation is used. It is easiest to just omit the argument when no special format is needed.
VB.NET program that uses empty format strings
Module Module1
Sub Main()
Dim testDate As DateTime = New Date(2019, 1, 1)
Dim nothingString As String = Nothing
' Test the ToString Function.
Console.WriteLine("NOTHING: {0}", testDate.ToString(nothingString))
Console.WriteLine("EMPTY: {0}", testDate.ToString(""))
Console.WriteLine("MISSING: {0}", testDate.ToString())
End Sub
End Module
Output
NOTHING: 1/1/2019 12:00:00 AM
EMPTY: 1/1/2019 12:00:00 AM
MISSING: 1/1/2019 12:00:00 AM
FormatException. Be careful to use a valid format string with DateTime. Some patterns, like the asterisk, will cause a FormatException—lower and uppercase letters should be used instead.
VB.NET program that causes FormatException
Module Module1
Sub Main()
Dim testDate As DateTime = New Date(2000, 1, 1)
Dim result As String = testDate.ToString("*")
End Sub
End Module
Output
Unhandled Exception: System.FormatException: Input string was not in a correct format.
at System.DateTimeFormat.GetRealFormat...
Format characters. You can use a variety of format characters on the DateTime type. For a more complete description, please view the article written for the C# language.
C# FormatNote: The formatting characters used in both languages are identical. The surrounding code syntax is the only difference.
A summary. This article demonstrated the correct use of format strings on the DateTime type. DateTime has many convenience functions, different format character styles and display options.
DateTime requires no custom code on our part. This makes programs easier to maintain and read. The DateTime formatting mechanism can handle most common cases.
Related Links:
- VB.NET Nullable
- VB.NET Convert Char Array to String
- VB.NET Object Array
- VB.NET File.ReadAllText, Get String From File
- VB.NET Compress File: GZipStream Example
- VB.NET Console.WriteLine (Print)
- VB.NET File.ReadLines Example
- VB.NET AddressOf Operator
- VB.NET Recursion Example
- VB.NET Recursive File Directory Function
- VB.NET Regex, Read and Match File Lines
- VB.NET Regex.Matches Quote Example
- VB.NET Regex.Matches: For Each Match, Capture
- VB.NET Convert String, Byte Array
- VB.NET File Size: FileInfo Example
- VB.NET File Handling
- VB.NET String.Format Examples: String and Integer
- VB.NET SyncLock Statement
- VB.NET TextInfo Examples
- VB.NET Array.Copy Example
- VB.NET HtmlEncode, HtmlDecode Examples
- VB.NET HtmlTextWriter Example
- VB.NET Stack Type
- VB.NET Func, Action and Predicate Examples
- VB.NET Function Examples
- VB.NET GoTo Example: Labels, Nested Loops
- VB.NET Array.Find Function, FindAll
- VB.NET HttpClient Example: System.Net.Http
- VB.NET DataColumn Class
- VB.NET DataGridView
- VB.NET DataSet Examples
- VB.NET DataTable Select Function
- VB.NET DataTable Examples
- VB.NET Attribute Examples
- VB.NET OpenFileDialog Example
- VB.NET Benchmark
- VB.NET BinaryReader Example
- VB.NET BinarySearch List
- VB.NET BinaryWriter Example
- VB.NET Regex.Replace Function
- VB.NET Regex.Split Examples
- VB.NET Regex.Match Examples: Regular Expressions
- VB.NET Convert ArrayList to Array
- VB.NET Array Examples, String Arrays
- VB.NET ArrayList Examples
- VB.NET Boolean, True, False and Not (Return True)
- VB.NET Nothing, IsNothing (Null)
- VB.NET Directive Examples: Const, If and Region
- VB.NET Do Until Loops
- VB.NET Do While Loop Examples (While)
- VB.NET Array.Resize Subroutine
- VB.NET Chr Function: Get Char From Integer
- VB.NET Class Examples
- VB.NET IndexOf Function
- VB.NET Insert String
- VB.NET Interface Examples (Implements)
- VB.NET 2D, 3D and Jagged Array Examples
- VB.NET Enum.Parse, TryParse: Convert String to Enum
- VB.NET Remove HTML Tags
- VB.NET Remove String
- VB.NET Event Example: AddHandler, RaiseEvent
- VB.NET Excel Interop Example
- VB.NET StartsWith and EndsWith String Functions
- VB.NET Initialize List
- VB.NET Number Examples
- VB.NET Optional String, Integer: Named Arguments
- VB.NET Replace String Examples
- VB.NET Exception Handling: Try, Catch and Finally
- VB.NET Enum Examples
- VB.NET Enumerable.Range, Repeat and Empty
- VB.NET Dictionary Examples
- VB.NET Double Type
- VB.NET LSet and RSet Functions
- VB.NET LTrim and RTrim Functions
- VB.NET Alphanumeric Sorting
- VB.NET PadLeft and PadRight
- VB.NET String.Concat Examples
- VB.NET String
- VB.NET Math.Abs: Absolute Value
- VB.NET Array.IndexOf, LastIndexOf
- VB.NET Remove Duplicate Chars
- VB.NET If Then, ElseIf, Else Examples
- VB.NET ParamArray (Use varargs Functions)
- VB.NET Integer.Parse: Convert String to Integer
- VB.NET ThreadPool
- VB.NET Process Examples (Process.Start)
- VB.NET TimeZone Example
- VB.NET Path Examples
- VB.NET ToArray Extension Example
- VB.NET ToCharArray Function
- VB.NET Stopwatch Example
- VB.NET Button Example
- VB.NET StreamReader ReadToEnd Function
- VB.NET ByVal Versus ByRef Example
- VB.NET StreamReader Example
- VB.NET StreamWriter Example
- VB.NET String.Compare Examples
- VB.NET Cast: TryCast, DirectCast Examples
- VB.NET String Constructor (New String)
- VB.NET String.Copy and CopyTo
- VB.NET Math.Ceiling and Floor: Double Examples
- VB.NET Math.Max and Math.Min
- VB.NET WebClient: DownloadData, Headers
- VB.NET Math.Round Example
- VB.NET Math.Truncate Method, Cast Double to Integer
- VB.NET Reverse String
- VB.NET Structure Examples
- VB.NET Sub Examples
- VB.NET Substring Examples
- VB.NET Convert Dictionary to List
- VB.NET Convert List and Array
- VB.NET Convert List to String
- VB.NET Convert Miles to Kilometers
- VB.NET Property Examples (Get, Set)
- VB.NET Remove Punctuation From String
- VB.NET Queue Examples
- VB.NET Const Values
- VB.NET Remove Duplicates From List
- VB.NET IComparable Example
- VB.NET ReDim Keyword (Array.Resize)
- VB.NET Contains Example
- VB.NET IEnumerable Examples
- VB.NET IsNot and Is Operators
- VB.NET String.IsNullOrEmpty, IsNullOrWhiteSpace
- VB.NET ROT13 Encode Function
- VB.NET StringBuilder Examples
- VB.NET Image Type
- VB.NET Val, Asc and AscW Functions
- VB.NET String.Empty Example
- VB.NET String.Equals Function
- VB.NET VarType Function (VariantType Enum)
- VB.NET With Statement
- VB.NET WithEvents: Handles and RaiseEvent
- VB.NET String Length Example
- VB.NET ToList Extension Example
- VB.NET ToLower and ToUpper Examples
- VB.NET TextBox Example
- VB.NET ToString Overrides Example
- VB.NET ToTitleCase Function
- VB.NET Convert String Array to String
- VB.NET Iterator Example: Yield Keyword
- VB.NET Mid Statement
- VB.NET Mod Operator (Odd, Even Numbers)
- VB.NET Convert String to Integer
- VB.NET Module Example: Shared Data
- VB.NET Integer
- VB.NET Keywords
- VB.NET Lambda Expressions
- VB.NET LastIndexOf Function
- VB.NET String Join Examples
- VB.NET Multiple Return Values
- VB.NET MustInherit Class: Shadows and Overloads
- VB.NET Namespace Example
- VB.NET KeyValuePair Examples
- VB.NET Environment.NewLine: vbCrLf
- VB.NET Levenshtein Distance Algorithm
- VB.NET Shared Function
- VB.NET Shell Function: Start EXE Program
- VB.NET Sleep Subroutine (Pause)
- VB.NET Sort Dictionary
- VB.NET Exit Statements
- VB.NET LINQ Examples
- VB.NET List Examples
- VB.NET Extension Method
- VB.NET Select Case Examples
- VB.NET MessageBox.Show Examples
- VB.NET Timer Examples
- VB.NET TimeSpan Examples
- VB.NET BackgroundWorker
- VB.NET String Between, Before and After Functions
- VB.NET CStr Function
- VB.NET DataRow Field Extension
- VB.NET DataRow Examples
- VB.NET DateTime Format
- VB.NET Char Examples
- VB.NET DateTime.Now Property (Today)
- VB.NET DateTime.Parse: Convert String to DateTime
- VB.NET DateTime Examples
- VB.NET Decimal Type
- VB.NET HashSet Example
- VB.NET Hashtable Type
- VB.NET Fibonacci Sequence
- VB.NET XmlWriter, Create XML File
- VB.NET File.Copy: Examples, Overwrite
- VB.NET File.Exists: Get Boolean
- VB.NET Path.GetExtension: File Extension
- VB.NET Tuple Examples
- VB.NET Trim Function
- VB.NET TrimEnd and TrimStart Examples
- VB.NET Word Count Function
- VB.NET Word Interop Example
- VB.NET For Loop Examples (For Each)
- VB.NET XElement Example
- VB.NET Truncate String
- VB.NET Sort Number Strings
- VB.NET Sort Examples: Arrays and Lists
- VB.NET SortedList
- VB.NET SortedSet Examples
- VB.NET Split String Examples
- VB.NET Uppercase First Letter
- VB.NET XmlReader, Parse XML File
- VB.NET ZipFile Example
- VB.NET Array.Reverse Example
- VB.NET Random Lowercase Letter
- VB.NET Byte Array: Memory Usage
- VB.NET Byte and Sbyte Types
- VB.NET Char Array
- VB.NET Random String
- VB.NET Random Numbers
- VB.NET Async, Await Example: Task Start and Wait
- VB.NET Choose Function (Get Argument at Index)
- VB.NET Sort by File Size
- VB.NET Sort List (Lambda That Calls CompareTo)
- VB.NET List Find and Exists Examples
- VB.NET Math.Sqrt Function
- VB.NET Loop Over String: For, For Each
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf