1

How can I convert a textbox string to datetime in asp.net c# ?

I tried this:

DateTime d2 = Convert.ToDateTime(tbx_Created.Text);
string createdformatted = d2.ToString("MM/dd/yyyy hh:mm:ss tt");
DateTime CreatdDate = DateTime.ParseExact(tbx_Created.Text, "MM/dd/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture); 

but it shows this error:

String was not recognized as a valid DateTime

I have given 15-6-2016 to textbox.

Please advise.

2
  • 1
    Food for thought: I have given 15-6-2016 to textbox, DateTime.ParseExact(..., "MM/dd/yyyy hh:mm:ss tt") notice something? Commented Jun 15, 2016 at 7:28
  • you are passing a date but trying to parse a time as well, remove everything except MM/dd/yyyy.. I'm guessing this is what @Manfred pointed out as well :) Commented Jun 15, 2016 at 7:31

7 Answers 7

2

You can parse user input like this:

DateTime enteredDate = DateTime.Parse(enteredString);

If you have a specific format for the string, you should use the other method:

DateTime loadedDate = DateTime.ParseExact(loadedString, "d", null);

Your formats input should match the Exact:

DateTime.ParseExact("24/01/2013", "dd/MM/yyyy");

source

Sign up to request clarification or add additional context in comments.

Comments

1

For "15-6-2016" input, datetime pattern should be "d-M-yyyy"

   DateTime CreatdDate = DateTime.ParseExact(tbx_Created.Text, 
     "d-M-yyyy", 
     System.Globalization.CultureInfo.InvariantCulture); 

You can try apply several patterns in one go, like this:

   DateTime CreatdDate = DateTime.ParseExact(tbx_Created.Text, 
     new String[] {
       "MM/dd/yyyy hh:mm:ss tt", // your initial pattern, recommended way
       "d-M-yyyy"},              // actual input, tolerated way
     System.Globalization.CultureInfo.InvariantCulture,
     DateTimeStyles.AssumeLocal); 

Comments

0

You are using MM for month while value of month is 6 not 06 so you need to use M for month.

DateTime dt = DateTime.Now;
DateTime.TryParseExact(tbx_Created.Text, "dd-M-yyyy", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

Comments

0
DateTime CreatdDate = DateTime.ParseExact(tbx_Created.Text, "d-M-yyyy", null);

Comments

0

Parse with exact format using ParseExact. But before parsing check if it is parsing will be valid using TryParseExact

if (!DateTime.TryParseExact("15-6-2016", "dd-M-yyyy",null))
{
    myDate = DateTime.ParseExact("15-6-2016", "dd-M-yyyy", null);
    Console.WriteLine(myDate);
}

Comments

0
DateTime datetime = Convert.ToDateTime(txbx_created.Text);
String CurrentTime = String.Format("{0:MM/dd/yyyy HH:mm}", datetime);

Comments

0
DateTime d2= DateTime.Parse(tbx_Created.Text);

A better way would be this:

DateTime d2;
if (!DateTime.TryParse(tbx_Created.Text, out myDate))
{
    // handle parse failure
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.