Asp.net mvc 5在添加内容时添加了时间戳?

Car*_*ate 3 c# asp.net asp.net-mvc asp.net-mvc-5

假设我的网站上有一个评论部分存储在数据库中.当我添加新评论时,我想看看谁添加了它以及他/她发布的日期/时间.

我不确定如何继续这样做.谁能把我推向正确的方向?

我知道我可以做到这一点. public DateTime Time { get; set; } 然而,如果用户输入他自己的日期,我需要自动化.

这是我尝试的模型,它不编译,而是生成Error 3 The type name 'Now' does not exist in the type 'System.DateTime':

public class Suggestion {
    public int Id { get; set; } 
    public string Comment { get; set; } 
    public DateTime.Now Time { get; set; } 
}
Run Code Online (Sandbox Code Playgroud)

这就是我得到的错误 Error 3 The type name 'Now' does not exist in the type 'System.DateTime'

tom*_*ich 6

如果您希望它每次都自动运行,您应该WhenCreated在构造函数中进行设置.这样您就不必记住在任何地方设置它.

public class Suggestion 
{
  public DateTime WhenCreated { get; set; }
  /* other props */

  public Suggestion() 
  {
    WhenCreated = DateTime.Now;
  }
}
Run Code Online (Sandbox Code Playgroud)

Suggestion从数据库记录中重新水化时,WhenCreated将由EntityFramework或您正在使用的任何持久层更新.在调用构造函数之后会发生这种情况,因此无论您具有什么初始值都无关紧要.当您的应用程序创建新应用程序时Suggestion,该WhenCreated字段将自动设置为"立即".

注意:DateTime.Now返回服务器时区的当前日期和时间.您可能需要为您的用户处理本地时区的转换,如果是这种情况,最好使用DateTime.UtcNowUTC时间,以便将来更容易本地化(在一段时间内不会加倍/丢失一小时) DaylightSaving移动)