0

I tried to make my CreatedDate column to be null or at least show the current date when I launch the application instead of 01/01/0001. I tried the example in Format MVC default Date (01/01/0001) to be empty and by adding a dot notation "newPerson.StartDate.Now" to the column on the razor page which wasn't working either.

SQLBen
  • 163
  • 1
  • 9

1 Answers1

2
public DateTime? MyDate { get; set; }

In your constructor of your object:

MyDate = null;

Or if you want to use a date

MyDate = DateTime.Now;

I just tested and both work for me.

  • There is zero point in initializing with null, since the default is null. Also, if you do want it to default to now, specify a property default; don't initialize in the constructor, i.e.: `public DateTime? MyDate { get; set; } = DateTime.UtcNow;`. Finally, don't use `DateTime.Now` in a server environment, especially. `Now` will be server time, which is almost assuredly not the same as the end-user's time. Use `UtcNow` and convert from UTC to the appropriate timezone when displaying the date/time. – Chris Pratt Mar 31 '20 at 18:39
  • It worked! However, MyDate = null did not work for me because The table is set not to accept nuul value. – SQLBen Mar 31 '20 at 18:41
  • Again, don't set it to null. There's no point. If you need to enforce that it has a value, despite being nullable, use the `Required` attribute on the property. – Chris Pratt Mar 31 '20 at 18:45