News:

Choose a design and let our professionals help you build a successful website   - ITAcumens

Main Menu

Convert Date/Time values into strings in VB.NET

Started by dhilipkumar, Nov 26, 2008, 08:27 PM

Previous topic - Next topic

dhilipkumar

Working with standard format strings
You can convert a Date/Time value into a string by overloading a version of the ToString method, which accepts a format string.

There are two types of Date/Time format strings: standard and custom. The standard format strings use one of the predefined formats and are specified by a letter corresponding to a particular format. When converting a Date/Time value to a string, the letter specifying one of the standard formats is used to refer to a particular format specifier. Here's a list of the standard date format specifiers



  • d: short date
    D: long date
    t: short time
    T: long time
    f: full Date/Time with short time
    F: full Date/Time with long time
    g: general Date/Time with short time
    G: general Date/Time with long time
    M or m: month day
    R or r: RFC1123
    s: sortable Date/Time that conforms to ISO 8601
    u: universal sortable Date/Time
    U: full Date/Time with long time. (This format is the same as F, but it uses universal GMT time.)
    Y or y: year month


Control Panel settings
The settings in the Control Panel's Regional and Language Options section influence the result you get when formatting a Date/Time value. The settings are used to initialize the DateTimeFormatInfo object, which is associated with the current thread culture and provides the values that control the formatting.

Dim dateTimeInfo as DateTime = DateTime.Now
MessageBox.Show (dateTimeInfo)



Dim strMonth as String = dateTimeInfo.ToString("m")
MessageBox.Show(strMonth)


The code defines the DateTime variable dateTimeInfo and sets its value to the current Date/Time. Then, I define the String variable strMonth and convert the value of dateTimeInfo into a String in a Month format.

Custom Date/Time format specifiers
You can also create custom format strings when the available standard format strings don't satisfy your needs. A custom Date/Time format string consists of one or more custom Date/Time format specifiers and defines how the Date/Time data would be formatted. For a full list of custom format specifiers, visit MSDN.