Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime shows the date as 01/01/0001

Tags:

c#

datetime

Sorry if this seems as a stupid question, but I cannot find an answer anywhere and I am a bit of a newbie. DateTime shows to be what I surmised as the Min Date. For instance:

DateTime updatedDate = new DateTime();
outItem.AddDate = updatedDate.ToLongDateString();

The output comes out to January 01, 0001. I've tried many variations of this with similar results. What am I doing wrong?

like image 717
droog114 Avatar asked Dec 03 '22 06:12

droog114


2 Answers

It depends on what you mean by "wrong". new DateTime() does indeed have the same value as DateTime.MinValue. If you want the current time, you should use:

DateTime updatedDate = DateTime.Now;

or

DateTime updatedDate = DateTime.UtcNow;

(The first gives you the local time, the second gives you the universal time. DateTime is somewhat messed up when it comes to the local/universal divide.)

like image 146
Jon Skeet Avatar answered Dec 13 '22 01:12

Jon Skeet


If you're looking to get the current date, use DateTime.Now. You're creating a new instance of the date class, and the min value is its default value.

DateTime updatedDate = DateTime.Now;
outItem.AddDate = updatedDate.ToLongDateString();

EDIT: Actually, you can shorten your code by just doing this:

outItem.AddDate = DateTime.Now.ToLongDateString();
like image 21
Tim Coker Avatar answered Dec 13 '22 02:12

Tim Coker