DateTime issue

Peter_1985 2,486 Reputation points
2022-08-06T09:05:30.1+00:00

Hi,
I've got the error below

at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)
at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)

on the return line below. Please help.

228715-image.png

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,367 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,235 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,036 Reputation points
    2022-08-06T09:20:46.643+00:00

    I would recommend something along these lines where the following is a mockup focused on the date.

    /// <summary>  
    /// Demo to insert new record, get new primary key  
    /// (You should have a primary key)  
    /// </summary>  
    /// <param name="dateTime">Valid DateTime</param>  
    /// <returns>Caller deconstructs</returns>  
    public static (int? id, Exception exception) InsertExample(DateTime dateTime)  
    {  
        using var cn = new SqlConnection(ConfigurationHelper.ConnectionString());  
        using var cmd = new SqlCommand { Connection = cn };  
      
        cmd.CommandText = @"INSERT INTO dbo.err (dt) VALUES (@dt);SELECT CAST(scope_identity() AS int);";  
      
        cmd.Parameters.Add("@dt", SqlDbType.DateTime).Value = dateTime;  
        try  
        {  
            cn.Open();  
            return (Convert.ToInt32(cmd.ExecuteScalar()), null);  
        }  
        catch (Exception ooopsException)  
        {  
            return (null, ooopsException);  
        }  
      
    }  
    

    Mock-up where you replace string value with your source

    string value = "08/08/2022";  
      
    if (DateTime.TryParse(value, out var dateTime))  
    {  
        var (id, exception) = InsertExample(dateTime);  
        if (exception is not null)  
        {  
            // handle exception  
        }  
        else  
        {  
            // success  
        }  
    }  
    
    1 person found this answer helpful.
    0 comments No comments