Let's say I have a comment section on my website that get stored in the database. When I add a new comment I would like to see who did add it and at what date / time he / she did post it.
Not sure how I would go ahead and do that. Anyone that can push me into the right dirrection ?
I am aware I can do this.       public DateTime Time { get; set; }
How ever that would end up with the user entering his own date, I need to be automatic.
Here is the model I tried, which does not compile, but instead generates 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; } 
}
And this is the error I get Error  3   The type name 'Now' does not exist in the type 'System.DateTime'
If you want it to run automatically and every time, you should set WhenCreated in the the constructor. This way you don't have to remember to set it anywhere.
public class Suggestion 
{
  public DateTime WhenCreated { get; set; }
  /* other props */
  public Suggestion() 
  {
    WhenCreated = DateTime.Now;
  }
}
When rehydrating a Suggestion from a database record, WhenCreated will be updated by EntityFramework or whatever persistence layer you are using. This occurs after the Constructor is called, so whatever initial value you have in there won't matter. When your application is creating a new Suggestion, the WhenCreated field will be automatically set to Now. 
Note: DateTime.Now returns the current date and time of the server's timezone. You may need to handle translation to local timezones for your users, and if that's the case, it might be good to use DateTime.UtcNow to get the UTC time which will be easier to localize in the future (won't double up/lose an hour during DaylightSaving moves)
public class Suggestion {
  public int Id { get; set; } 
  public string Comment { get; set; } 
  public DateTime Time { get; set; } 
}
Suggestion s = new Suggestion();
s.Time = DateTime.Now;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With