I have come across reasons to convert a formatted string into a valid DateTime object in .NET. I have done this several times during last few years, but every time when I have to do it again, I have to depend on Google to find the trick.
So, this time, after spending 15 minutes to figure out this silly thing, I decided to post it here so that at least I can find it again when I want. I am sure this will help others too!
The following sample VB.NET code shows how to convert a string to a date time object.
Make sure you import the name space:
Imports System.Globalization
Here is the sample code that converts a string to a datetime object.
Try Dim dateString = "25/11/2006 11:45 PM" Dim formats As String() = {"dd/MM/yyyy hh:mm tt", "dd/MM/yy hh:mm tt"} Dim dateObject As DateTime = DateTime.ParseExact(dateString, formats, System.Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.NoCurrentDateDefault) MessageBox.Show(dateObject.ToString("dd/MM/yyyy HH:mm")) Catch ex As FormatException MessageBox.Show( "Please enter valid date in dd/mm/yyyy format.") End Try
The above sample outputs the following:
25/11/2006 23:45
The sample supports the following formats:
dd/MM/yyyy hh:mm tt dd/MM/yy hh:mm tt
You can change the formats variable to support a variety of formats and change the separator to anything you want.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|