Asp.net mvc 5 adding a time stamp to when things were added?

12,387

Solution 1

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)

Solution 2

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;
Share:
12,387
Carlssonthepirate
Author by

Carlssonthepirate

Updated on June 28, 2022

Comments

  • Carlssonthepirate
    Carlssonthepirate almost 2 years

    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'

  • Carlssonthepirate
    Carlssonthepirate almost 9 years
    But in order to make a new instance of the Suggestion class I have to be in another class, would that not create two tables in my DB ?
  • vmg
    vmg almost 9 years
    what do you mean by "to be in another class"?
  • Claies
    Claies almost 9 years
    @Carlssonthepirate this was a trivial example, if you already have an instance of the class which is holding the other data the user filled in, simply update the property on that instance....
  • vmg
    vmg almost 9 years
    it won't create two tables in db.