Visual Basic 2010 Lesson 16 – Functions Part V- Formatting Date and Time

[Lesson 15] << [CONTENTS] >> [Lesson 17]

16.1 Formatting Date and time using predefined formats

In Visual Basic 2010, date and time can be formatted using predefined formats and also user-defined formats. The predefined formats of date and time are shown in Table 16.1.

Visual Basic 2010

* Instead of “General date”, you can also use the abbreviated format “G” , i.e. Format (Now, “G”). And for “Long Time”, you can use the abbreviated format “T”. As 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 the diagram below:

Visual Basic 2010

16.2 Formatting Date and time using user-defined formats

Beside 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)

Visual Basic 2010

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 diagram below:

[Lesson 15] << [CONTENTS] >> [Lesson 17]

Google+Sina WeiboGoogle GmailYahoo MailPrintLinkedInPinterestTumblrQQShare

Please write your comment and share your ideas here :