【问题标题】:Get date part of date time获取日期时间的日期部分
【发布时间】:2017-08-15 16:22:49
【问题描述】:

我有 web api 控制器,我需要将日期写入表格。

我试着这样做

[ResponseType(typeof(TimeTable))]
    public IHttpActionResult PostStartPause(TimeTable startPause)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        if (ModelState.IsValid)
        {
            DateTime dt = DateTime.Today.Date; 
            TimeTable c = (from x in db.TimeTables
                where x.Company == startPause.Company && x.INN == startPause.INN
                select x).First();
            c.StartPause = startPause.StartPause;
            c.Today = dt;
            db.SaveChanges();
        }
        //db.TimeTables.Add(startPause);
        //db.SaveChanges();
        return Json(new { Result = "Success", Message = "Saved Successfully" });
        // return CreatedAtRoute("DefaultApi", new { id = startPause.Id }, startPause);
    }

对于日期部分,我尝试使用此代码

 DateTime dt = DateTime.Today.Date;

但它会写日期和时间

这是 TimeTable 类

 public partial class TimeTable
{
    public int Id { get; set; }
    public string Company { get; set; }
    public string INN { get; set; }
    public string StartDay { get; set; }
    public string StartPause { get; set; }
    public string EndDay { get; set; }
    public string EndPause { get; set; }
    public Nullable<System.DateTime> Today { get; set; }
}

如何只将日期写入数据库?

【问题讨论】:

  • 因为DateTime 总是有一个时间分量。如果您想在没有“时间”的情况下将值存储在数据库中,请将字段 DATE 类型(SqlServer)
  • 数据库中的Today 列是否设置为datetime 类型?尝试将其更改为 date(C# 只有 DateTime)。
  • 或者您可以将其转换为字符串DateTime.Today.Date.ToString("yyyyMMddHHmmss"); // case sensitive,然后在Sql Server中编写一个触发器来处理它,即进行反向转换

标签: c# asp.net-mvc asp.net-web-api


【解决方案1】:

只获取日期:

DateTime.Today.ToShortDateString()

【讨论】:

    【解决方案2】:

    您必须检查数据库服务器上的表架构,显然字段数据类型设置为DateTime,而不是您可以使用Date

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 1970-01-01
      • 2016-10-17
      • 2015-08-15
      相关资源
      最近更新 更多