VB.Net - DataTypes - DateTime

Here is a sample of the datetime variable

1
2
3
4
dim dt as datetime = now


? dt.tostring("d")

The datetime data type has a toString function which can take a formatting character. Here are some of the codes:

  • “d” - 2/6/2004 (aka short date pattern)
  • “f” - Mondy, February 6, 2006 12:00 am - (Full short)
  • “D” - aka Long Date pattern
  • “t” - short time
  • “T” - long time
  • “F” - Long full

Note

lSsoStartDate_Time.Text = dt.ToString("t")

and

lblSsoStartDate_Time.Text = dt.ToString("t", System.Globalization.DateTimeFormatInfo.InvariantInfo)

Give 2 different results. (one is 4:36pm other is 16:36)

See “Standard Datetime format strings”

You can also do

1
? dt.tostring("MMddyy")

to get an output like 050807

1
? dt.tostring("MMyy")

to get an output like 0507

1
? dt.tostring("MM/yyyy")

to get an output like 05/2007

1
? datediff(dateinterval.Year, cdate("12/31/2003", cdate("1/1/2004"))

returns 1

You can also use the format function to format dates

For example

1
response.write Format(DateAdd(DateInterval.Hour, 2, CDate(txtFrom.Text.ToString)), "hh:mm")

This will add two hours from a text box control and then display the hours:minutes

On a datagrid you can use a Data Formatting Expression of {0:MM/dd/yy}