Issue to date time field

Peter_1985 2,506 Reputation points
2022-07-25T04:49:33.333+00:00

Hi,
I get the issue below

String was not recognized as a valid DateTime. at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)

When I have the value like

7/1/2021 12:00:00 AM

to the field.

Here is of the code the line leading to the issue.

224146-image.png

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,254 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,247 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,036 Reputation points
    2022-07-28T10:10:50.7+00:00

    I would recommend using DateTime.TryParse to ensure there is a proper DateTime.

    Get user input, assert text is a DateTime and if so pass to a method, in this case in the second code block the data operation is inserting a new record but the same applies for updates too.

    if (DateTime.TryParse(TextBox1.Text.Trim(), out var dateTime))  
    {  
        var (success, exception, id) = DataOperations.AddNewRecord(dateTime);  
        if (success)  
        {  
            // we can use id var  
        }  
        else  
        {  
            // failure - log error using exception var about  
        }  
    }  
    else  
    {  
        // not a valid date time, tell the user  
    }  
    

    Backend code

    public class DataOperations  
    {  
      
    	private static string _connectionString =  
    		"Data Source=.\\sqlexpress;Initial Catalog=Examples;Integrated Security=True";  
      
    	public static (bool success, Exception exception, int id) AddNewRecord(DateTime dateTime)  
    	{  
    		using var cn = new SqlConnection { ConnectionString = _connectionString };  
    		using var cmd = new SqlCommand { Connection = cn };  
    		cmd.CommandText = "INSERT INTO dbo.Table1 (SomeDateTime) " +  
    						  "VALUES (@SomeDateTime);" +  
    						  "SELECT CAST(scope_identity() AS int);";  
      
    		cmd.Parameters.Add("@SomeDateTime", SqlDbType.DateTime).Value = dateTime;  
      
    		try  
    		{  
    			cn.Open();  
    			return (true, null, Convert.ToInt32(cmd.ExecuteScalar()));  
      
    		}  
    		catch (Exception ex)  
    		{  
    			return (false, ex, -1);  
    		}  
    	}  
    }  
    
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Rafael da Rocha 5,076 Reputation points
    2022-07-25T05:16:11.26+00:00

    ParseExact would be expecting a leading 0 on dd/MM. try d/M/yyyy.


  2. Lan Huang-MSFT 25,551 Reputation points Microsoft Vendor
    2022-07-25T06:58:39.22+00:00

    Hi @Peter_1985 ,

    String was not recognized as a valid DateTime

    As the error says, the string is not a valid datetime.
    Your format string is missing the time format and AM/PM deisgnator, and the day and month are reversed and the numbers don't match.
    The correct one should be: M/d/yyyy hh:mm:ss tt

     //String = "7/1/2021 12:00:00 AM";    
    cmd3.Parameters.Add("@vaild_from", SqlDbType.DateTime).Value = DateTime.ParseExact(TextBox1.Text.Trim(), "M/d/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);  
        //String = "07/01/2021 12:00:00 AM";    
    cmd3.Parameters.Add("@vaild_from", SqlDbType.DateTime).Value = DateTime.ParseExact(TextBox1.Text.Trim(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);  
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.