ASP.NET MVC:无法从 SQL 数据库中检索小时、分钟、秒,它们总是显示 12:00

ASP.NET MVC : cannot retrieve hours, minutes, seconds from SQL database, they always show 12:00

注意:我也在寻找一种方法 AddWithParameter 来避免 SQL 注入风险,但我不确定该怎么做与 DotNetNuke 所以这是这个问题的第二个问题。

我将日期作为 C# DateTime 存储到 SQL 数据库 datetime 列中。检索该日期时无法获取 hh:mm:ss 信息,它始终显示 12:00,但检索并正确显示日、月、年。

这是我在 SQL 中插入日期的方式:

string sqlDateFormat = "yyyy-MM-dd HH:mm:ss.fff";               
string sqlInsertString = String.Format("INSERT INTO TABLE_NAME (Date_Column_Name) VALUES ({0})", thisDate?.ToString(sqlDateFormat)};

using (IDataContext ctx = DataContext.Instance())
{
    try
    {                  
        ctx.Execute(System.Data.CommandType.Text, 
        sqlInsertString);      
        success = true;                                                     
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
    }
}

这是我检索 table 数据的方式:

using (IDataContext ctx = DataContext.Instance())
{
    string sqlString = @"SELECT Date_Column_Name FROM Table_Name  WHERE ID = " + paramId;

    try
    {
        myTableDates = ctx.ExecuteQuery<TableModel> (System.Data.CommandType.Text, sqlString);
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
    }
}

这是我尝试在视图中显示的方式:

<tbody>
    @foreach (TableModel tm in Model.AllTablesDates)
    {
        var dateVar = tm.Date == null ? "N/A" : 
        tm.Date.Value.ToString("dd-MMM-yyyy h:mm tt");

        <tr>
            <td data-title="Day">@dateVar</td>                        
        </tr>
    }
</tbody>

基于 this post 将您的陈述更改为以下内容:

ctx.Execute("INSERT INTO TABLE_NAME (Date_Column_Name)VALUES (@0)", thisDate);