How to Convert Time Strings in Vb.Net

How to Convert Time Strings in Vb.Net thumbnail
Ensuring a valid date is highly important in financial software.

Data gets validated and manipulated a lot within the logic of a computer program. Many times data is accepted in one format but must be converted to another format for a calculation to be performed, or to concatenate two or three values or possibly for display or storage purposes. There are many reasons why data types need to be changed and thus VB.NET provides many functions to perform these various conversions.

Instructions

  1. Convert Date/Time To String

    • 1

      Accept a value that is of type "DateTime" into your program and create a variable to store that value. An example of a variable name is "inputDateTime". Set "inputDateTime" equal to the user input. This can also be input from a variety of sources including a file or database.

    • 2

      Define a variable of type "String." An example of a variable name for this value is "myDateTimeString". Set "myDateTimeString" equal to "inputDateTime.ToString" and pass a valid standard date format specifier to the "ToString" method. For example, "inputDateTime.ToString("M")" will put the month and day into "myDateTimeString" variable.

    • 3

      Define as many string variables as necessary and in any format that is necessary for your program logic. The original input data type remains "DateTime" data type.

    Convert A String To A DateTime

    • 4

      Declare a variable of type "String" to hold an input value, from the user, a database, file or elsewhere. The string needs to be in a proper date format. Examples of date formats accepted are: "2011-01-05", "January 25, 1992", "7:43:00 PM", "Fri, 18 March 2010 16:15:00 GMT".

    • 5

      Declare a variable of type "DateTime" to hold the value of the string after it has been converted to a "DateTime" data type. Set the "DateTime" variable equal to "DateTime.Parse(stringvalue)" where "stringvalue" is the string representation of a valid date. If the string is not a valid date, the "Parse" method will throw an error.

    • 6

      Catch any errors thrown from the "Parse" method. This is particularly important if accepting user input because unless the input field is designed as a "date" field, the user may enter anything. The best thing to do is to display a message to the user asking them to "Please enter a valid date and time".

Related Searches:

References

  • Photo Credit Jupiterimages/Photos.com/Getty Images

Comments

Related Ads

Featured