You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Entity Framework中结合指定日期与当前时间存入datetime字段?

实现指定日期与当前时间的结合存储

这问题其实挺常见的,核心就是把指定日期的日期部分和当前时间的时间部分拼接在一起,下面给你几种简单可靠的实现方式:

方法一:利用Date属性 + TimeOfDay

这种方式最简洁,利用DateTime的内置属性直接组合:

string value_date = "04/14/2018";
// 先解析指定日期(注意:如果系统文化不是MM/dd/yyyy,建议用ParseExact指定格式,后面会说)
DateTime specifiedDate = Convert.ToDateTime(value_date);
// 拼接指定日期的日期部分 + 当前时间的时分秒
DateTime combinedDateTime = specifiedDate.Date + DateTime.Now.TimeOfDay;

add.Order_Date = combinedDateTime;
db.Products.Add(add); // 你原代码里的db.Products(add)应该是笔误,正确是Add方法
db.SaveChanges();
  • specifiedDate.Date:提取指定日期的00:00:00时间点,只保留年/月/日信息
  • DateTime.Now.TimeOfDay:获取当前时间的时分秒(包括毫秒),比如15:42:30.567
  • 两者相加就得到了2018-04-14 15:42:30.567这样的组合时间

方法二:手动构造DateTime对象

如果你想更直观地控制每个时间部分,可以用DateTime的构造函数手动拼接:

string value_date = "04/14/2018";
DateTime specifiedDate = Convert.ToDateTime(value_date);
DateTime currentTime = DateTime.Now;

// 手动构造新的DateTime,年/月/日来自指定日期,时/分/秒/毫秒来自当前时间
DateTime combinedDateTime = new DateTime(
    specifiedDate.Year,
    specifiedDate.Month,
    specifiedDate.Day,
    currentTime.Hour,
    currentTime.Minute,
    currentTime.Second,
    currentTime.Millisecond
);

add.Order_Date = combinedDateTime;
db.Products.Add(add);
db.SaveChanges();

这种方式的好处是你可以灵活调整,比如不需要毫秒的话,直接去掉最后一个参数即可。

额外注意事项:日期解析的安全性

如果你的系统默认文化不是MM/dd/yyyy格式(比如欧洲常用dd/MM/yyyy),直接用Convert.ToDateTime可能会解析出错。建议用DateTime.ParseExact指定固定格式,确保解析准确:

DateTime specifiedDate = DateTime.ParseExact(
    value_date, 
    "MM/dd/yyyy", 
    System.Globalization.CultureInfo.InvariantCulture
);

另外,你的数据库字段是smalldatetime,它的精度是分钟,所以毫秒部分会被自动截断,最终存储的时间会是类似2018-04-14 15:42:00这样的格式,这是正常的。

内容的提问来源于stack exchange,提问作者Brian Crist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:33:04