Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
string was not recognized as valid DateTime


and my date string is 27/04/2014 00:00:00 A.M.


I don't know Why I'm getting this error


objrpt.ToDate = Convert.ToDateTime(txttodate.Text);

exception raising fro here not from db
Posted
Updated 13-Apr-14 21:31pm
v2
Comments
syed shanu 14-Apr-14 2:20am    
So what do you want and whare do you get this error and what you actualy need.
Sanket Saxena 14-Apr-14 3:00am    
We dont know what code you have written and what you are trying to do. Just share your code.

1. You have to check that the datetime string is a valid one using TryParse method;
2. If it is a valid datetime string, then do the conversion to datetime else abort.
C#
using System;

public class Program
{
    public static void Main()
    {
          string dateString = "27/04/2014 00:00:00 AM";

          Console.WriteLine("The original string is {0}", dateString);

          DateTime dt;

          if (DateTime.TryParse(dateString, out dt))
          {
               string format = "yyyy-MM-dd";
               // do something with dt

               Console.WriteLine(dt.ToString(format));
          }
          else
          {
              Console.WriteLine("Not a valid datetime");
          }
    }
}
 
Share this answer
 
It's getting error for datetime format because your string is in "dd/MM/yyyy" format

It will unable to convert datetime it needs like "MM/dd/yyyy" or "yyyy/MM/dd"
Hope so

Then you need to changes your string date="04/27/2014" like this
 
Share this answer
 
v2
Comments
Member 10690248 16-Apr-14 8:21am    
previously the same code worked fine
try this
string CrDate = Convert.ToDateTime("Your field").ToString();
 
Share this answer
 
The exception was raised by the database, not by ASP.Net. You tried to insert or update a datatime value, or tried to retrieve rows based on a datetime constraint (WHERE clause). I further conclude that you generated the SQL query by string concatenation, instead of using a parameterized query.
And that's the point: use a parameterized query. Beyond those annoying formatting issues, it will provide a good protection from SQL Injection attacks (a really important security issue)!
 
Share this answer
 
Comments
Member 10690248 14-Apr-14 3:31am    
objrpt.ToDate = Convert.ToDateTime(txttodate.Text);

exception raising fro here not from db
DateTime AppointmentDatetime = DateTime.ParseExact (tempdatetime,"dd/MM/yyyy hh:mm:ss tt" ,CultureInfo.InvariantCulture );
 
Share this answer
 
Comments
Member 10690248 16-Apr-14 8:36am    
but appointment date is in MM/dd/yyyy Format i need it in dd/mm/yyyy format

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900