Date conversion from C# to MySql Format

柔情痞子 提交于 2019-11-29 12:04:29

I haven't used MySQL with .NET, but Oracle has similar date conversion issues with .NET. The only way to stay snae with this has been to use parameters for date values, both for input as welll as for WHERE clause comparisons. A parameter created with a MySQL date parameter type, and just giving it a .NET datetime value, should work without needing you to do conversions.

EDITED TO ADD SAMPLE CODE

This code sample shows the basic technique of using parameters for DateTime values, instead of coding conversions to text values and embedding those text values directly in the SQL command text.

public DataTable GetAlertsByDate(DateTime start, DateTime end)
{
    SqlConnection conn = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand(
        "SELECT * FROM Alerts WHERE EventTime BETWEEN @start AND @end", conn);
    DataTable table = new DataTable();
    try
    {
        SqlParameter param;
        param = new SqlParameter("@start", SqlDbType.DateTime);
        param.Value = start;
        cmd.Parameters.Add(param);
        param = new SqlParameter("@end", SqlDbType.DateTime);
        param.Value = end;
        cmd.Parameters.Add(param);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(table);
    }
    finally
    {
        cmd.Dispose();
        conn.Close();
        conn.Dispose();
    }
    return table;
}

This is SQL Server code, but the technique should be the same for most databases. For Oracle, for example, the only changes would be to use Oracle data access objects, and use ":" in place of "@" in parameter names. The technique for MySQL should also be very similar.

For many databases, shortcuts may exist for creating parameters, such as:

cmd.Parameters.AddWithValue("@start", start);

This works when you know the value is not null, and the correct parameter type can be derived from the C# type of the value. "AddWithValue" is specific to SQL Server; "Add" works also but is obsolete in SQL Server.

Hope this helps.

You can assign format to data time, DateTime.ParseExact() or DateTime.ToString(format), :

the format for 2011-7-27 is yyyy-m-dd

I use:

string fieldate = dt1.ToString("yyyy-MM-dd");

Assuming you are doing this in the database I think you should use date_format to get in the required format

Something like date_format(dateval,'%Y-%c-%d') (Not tested)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!