Convert Date/Time values into strings in VB.NET

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

previous topic - next topic
Go Down

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.

Go Up
 

Quick Reply

With Quick-Reply you can write a post when viewing a topic without loading a new page. You can still use bulletin board code and smileys as you would in a normal post.

Warning: this topic has not been posted in for at least 120 days.
Unless you're sure you want to reply, please consider starting a new topic.

Note: this post will not display until it's been approved by a moderator.
Name:
Email:
Verification:
Please leave this box empty:

Type the letters shown in the picture
Listen to the letters / Request another image

Type the letters shown in the picture:

shortcuts: alt+s submit/post or alt+p preview