Dates in Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

This lesson describes the Dates in Visual Basic .NET

To represents an instant in time in Visual Basic .NET, you tipically use the DateTime Structure.

This structure supports many helpful methods that you can be used for various tasks like getting yesterday's date or the current month name.

When you declare the DateTime variable its default value is 1/1/0001, 12:00 AM midnight e.g.

Dim defaultDate As DateTime
Console.WriteLine(defaultDate.ToShortDateString & ", " & defaultDate.ToShortTimeString)  
' this code yields to 1/1/0001, 12:00 AM               

However you can easily set its value to Today's date:
Dim TodaysDate As DateTime = DateTime.Now
Console.WriteLine(TodaysDate.ToShortDateString & ", " & TodaysDate.ToShortTimeString)
' this code yields to 5/11/2014, 2:26 PM

Then you can go further and for example, get the Yesterday's date:
Dim YesterdayDate As DateTime = DateTime.Now.AddDays(-1)
Console.WriteLine(YesterdayDate.ToShortDateString & ", " & YesterdayDate.ToShortTimeString)
' this code yields to 5/10/2014, 2:26 PM

You can also display the result in a format defined by a specific format specifier e.g.

Dim TodaysDate As DateTime = DateTime.Now
' this code ALSO yields to 5/11/2014, 2:26 PM

You can additionally format your date using specific culture e.g.
Dim TodaysDate As DateTime = DateTime.Now
Console.WriteLine(TodaysDate.ToString("F"), New System.Globalization.CultureInfo("fr-FR"))
' this code yields to: dimanche 11 Mai, 14:26:00

Previous Lesson | Next Lesson

Share This

Home | About | Contact | Privacy Policy

Copyright 2018 - All Rights Reserved.