假设我的网站上有一个评论部分存储在数据库中。当我添加新评论时,我想看看是谁添加的以及他/她在什么日期/时间发布了它。
不确定我将如何继续这样做。任何人都可以将我推向正确的方向吗?
我知道我可以做到这一点。 public DateTime Time { get;放;
最终用户输入他自己的日期怎么办,我需要自动。
这是我试过的模型,它不编译,而是生成 错误 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; }
}
这是我得到的错误 Error 3 The type name 'Now' does not exist in the type 'System.DateTime'
最佳答案
如果你想让它每次都自动运行,你应该在构造函数中设置WhenCreated
。这样您就不必记得在任何地方设置它。
public class Suggestion
{
public DateTime WhenCreated { get; set; }
/* other props */
public Suggestion()
{
WhenCreated = DateTime.Now;
}
}
从数据库记录中提取建议
时,WhenCreated
将由 EntityFramework 或您正在使用的任何持久层进行更新。这是在调用 Constructor 之后发生的,因此无论您在其中拥有什么初始值都无关紧要。当您的应用程序正在创建新的 Suggestion
时,WhenCreated
字段将自动设置为 Now。
注意:DateTime.Now
返回服务器时区的当前日期和时间。您可能需要为您的用户处理本地时区的翻译,如果是这种情况,最好使用 DateTime.UtcNow
来获取 UTC 时间,这在将来更容易本地化(在夏令时移动期间不会加倍/损失一个小时)
关于c# - Asp.net mvc 5 在添加内容时添加时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30785521/