简体   繁体   English

DateTime将日期显示为01/01/0001

[英]DateTime shows the date as 01/01/0001

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. DateTime显示为我猜测的最小日期。 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. 输出到0001年1月1日。我尝试了很多变化,结果相似。 What am I doing wrong? 我究竟做错了什么?

It depends on what you mean by "wrong". 这取决于你所说的“错误”。 new DateTime() does indeed have the same value as DateTime.MinValue . new DateTime()确实具有与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.) (第一个给你当地时间 ,第二个给你通用时间。当涉及到本地/普遍鸿沟时, DateTime 有些混乱 。)

If you're looking to get the current date, use DateTime.Now . 如果您要获取当前日期,请使用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();

Jon Skeet says correct, and I have some to add. Jon Skeet说的正确,我还有一些要补充。

The "wrong" depends on what time you want to get. “错误”取决于你想要的时间。

The DateTime is a struct , and the the default contructor of a struct DateTime是一个struct ,是struct的默认构造函数

always initializes all fields to their zero for numeric type and null 始终将所有字段初始化为数字类型的零并且为null

for reference type. 作为参考类型。

so if you want to get the current local date and time, you can call static property DateTime.Now. 因此,如果要获取当前的本地日期和时间,可以调用静态属性DateTime.Now。

   var curDateTime = DateTime.Now;

if you want to get UTC time. 如果你想获得UTC时间。

   var utcDateTime = DateTime.UtcNow;

Note: the DateTime.UtcNow get the current date and time, but instead of using local time zone, it uses UTC time instead. 注意:DateTime.UtcNow获取当前日期和时间,但它不使用本地时区,而是使用UTC时间。

You can reference the link as below. 您可以参考以下链接。

http://blackrabbitcoder.net/archive/2010/11/18/c.net-little-wonders-datetime-is-packed-with-goodies.aspx http://blackrabbitcoder.net/archive/2010/11/18/c.net-little-wonders-datetime-is-packed-with-goodies.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM