Flávio Augusto Flávio Augusto - 6 months ago 17
ASP.NET (C#) Question

1 Line on controller to auto input datetime.now in new records

Some 3 days ago a friend helped me with this, but I needed to rebuild my controller and view and lost the command that auto input "datetime.now" when client create something new on web compiled
I remember that was a line on:

inside if

I'm from Brazil, sorry about some language errors.


First, please do not post code as an image. Your question itself, should include all relevant code in text.

That said, there's nothing really special here. If you want to set a property to DateTime.Now before saving in your controller, you just do that:

foo.CreatedDate = DateTime.Now;

However, it's better if you're going to do this with any frequency, to actually use a custom getter and setter on your property to handle this automatically:

private DateTime? createdDate;
public DateTime CreatedDate
    get { return createdDate ?? DateTime.Now; }
    set { createdDate = value; }

That way, if the property hasn't been explicitly set, it will automatically return DateTime.Now. After it has been set, it will return whatever it was set to.

Finally, you should avoid DateTime.Now. The value of that is the local server time, and really has no relevance to anything. If you ever co-locate your site on servers in different timezones, the value in the database quickly becomes meaningless. You should always use DateTime.UtcNow, which returns the current date and time in UTC, which will always be the same regardless of local server time. Or, if you insist on storing local time, then use DateTimeOffset.Now, so you'll at least have a timezone component to work with.