shary.sharath
shary.sharath

Reputation: 709

Error while converting textbox content to DateTime format in C# ASP.net

Hi i am developing an application, in that i required to store date in sql server 2005 database which is retrieved from a textbox in front end. In front end, user is allowed to pick a date from JQuery UI DatePicker plugin.

Error I am getting is as follows:

String was not recognized as a valid DateTime.

Code i have is:

db.eventDate = DateTime.Parse(txtDate.Text, new CultureInfo("en-US").DateTimeFormat);

Upvotes: 0

Views: 12172

Answers (6)

user1760979
user1760979

Reputation:

Try this code

string yourDate = txtDate.Text;
string formattedDate = yourDate.ToString("dd-MM-yyyy");
DateTime dt = DateTime.ParseExact(formattedDate , "dd-MM-yyyy", CultureInfo.InvariantCulture);

Upvotes: 1

shary.sharath
shary.sharath

Reputation: 709

i simply changed the date format of JQuery UI DatePicker in my code. Before it was in UK format so i was getting error while saving data to database. But once i change it to US format it working fine.

I thanks for everyone who reviewed my question and suggested me the answers.

Upvotes: 0

user3188781
user3188781

Reputation:

Hope following code helps you.

        Dim dt As New DateTime
        Dim txtDateFromUser As String = "04/09/2014"

        If DateTime.TryParse(txtDateFromUser, dt) = True Then

            Dim connStr As String
            connStr = System.Configuration.ConfigurationManager.ConnectionStrings("youConnectionStringName").ConnectionString

            'Insert into database
            Dim sqlconn As New SqlConnection
            sqlconn.ConnectionString = connStr
            Dim sqlcmd As New SqlCommand("insert into tblDateTime (dtTestDate) values ('" + dt.ToString() + "')")
            sqlconn.Open()
            sqlcmd.Connection = sqlconn
            sqlcmd.ExecuteNonQuery()

        End If

Here is the test table I've used:

        create table tblDateTime (dtTestDate datetime)

Upvotes: 0

Jameem
Jameem

Reputation: 1838

Try this..Working fine for me..

Convert.ToDateTime(txtDate.Text,System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormat);

or

Convert.ToDateTime(txtDate.Text);

Upvotes: 0

Damith
Damith

Reputation: 63105

you better use DateTime.ParseExact with the correct date time format you set to date time picker

for example if the format is "MM/dd/yyyy" you can do as below

db.eventDate =  DateTime.ParseExact(txtDate.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);

Upvotes: 0

sh1rts
sh1rts

Reputation: 1884

You should either use DateTime.TryParse(expression) or wrap your call to DateTime.Parse in a try/catch block. Just out of interest, can you post some example dates you're converting ? They are in US format, right ?

Upvotes: 0

Related Questions