C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Convert string to DateTime object


Posted Date: 22 Oct 2006    Resource Type: Articles    Category: .NET Framework
Author: Tony JohnMember Level: Diamond    
Rating: 1 out of 5Points: 10



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.



Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: .NET FAQS
Previous Resource: Session modes.
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use