VB2019 VB2017 VB2015 VB2013 VB2012 VB2010 VB2008 VB6 VB Sample Code 中文VB About Us

Lesson 16 : Formatting Date and Time


16.1 Formatting Date and time using predefined formats in Visual Basic 2012

In Visual Basic 2012 , we can format date and time using predefined formats or user-defined formats. The predefined formats of date and time are shown in Table 16.1.

Table 16.1 Predefined formats of date and time
Format Explanation
Format (Now, "General date") Formats the current date and time.
Format (Now, "Long Date") Displays the current date in long format
Format (Now, "Short date") Displays current date in short format
Format (Now, "Long Time") Display the current time in long format.
Format (Now, "Short Time") Display the current time in short format.

* Instead of "General date", you can also use the abbreviated format "G" , i.e. Format (Now, "G"). For "Long Time", you can use the abbreviated format "T" and for "Short Time", you may use the abbreviated format "t"

Example 16.1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
	Label1.Text = Format(Now, "General Date")
	Label2.Text = Format(Now, "Long Date")
	Label3.Text = Format(Now, "short Date")
	Label4.Text = Format(Now, "Long Time")
	Label5.Text = Format(Now, "Short Time")
End Sub

The output is shown in Figure 16.1.

Visual Basic 2012
Figure 16.1

16.2 Formatting Date and time using user-defined formats

Besides using the predefined formats, you can also use the user-defined formatting functions. The general syntax of a user-defined for date/time is

Format (expression,style)

Table 16.2 shows some of the user-defined format functions for date and time

Table 16.2 User-Defined Format Functions
Format Explanation
Format (Now,"M") Displays current month and date
Format (Now,"MM") Displays current month in double digits.
Format (Now, "MMM") Displays abbreviated name of the current month
Format (Now, "MMMM") Displays full name of the current month.
Format (Now,"dd/MM/yyyy") Displays current date in the day/month/year format.
Format (Now,"MMM,d,yyyy") Displays current date in the Month, Day, Year Format
Format (Now, "h:mm:ss tt") Dispalys current time in hour:minute:second format and show am/pm
Format (Now, "MM/dd/yyyy  h:mm:ss") Dispalys current date and time in hour:minute:second format

Example 16.2

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click
	Label1.Text = Format(Now, "M")
	Label2.Text = Format(Now, "MM")
	Label3.Text = Format(Now, "MMM")
	Label4.Text = Format(Now, "MMMM")
	Label5.Text = Format(Now, "dd/MM/yyyy")
	Label6.Text = Format(Now, "MMM,d,yyyy")
	Label7.Text = Format(Now, "h:mm:ss tt")
	Label8.Text = Format(Now, "MM/dd/yyyy h:mm:ss tt")
End Sub

The output is shown in the figure below:

Visual Basic 2012
Figure 16.2


❮ Previous Lesson Next Lesson ❯


Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy