[英]DateTime not adding time - Strange issue
Having this line of code:有这行代码:
DateTime inFutureDateTime = DateTime.Now.AddSeconds(60);
And writing in the (Unity) console like this并像这样在(Unity)控制台中编写
Debug.Log("In future date time " + inFutureDateTime.Date)
outputs:输出:
12/15/2021 12:00:00 AM
The Date is correct (today), but the time isn't.日期是正确的(今天),但时间不正确。 It should be CurrentTime + 60 seconds.
它应该是 CurrentTime + 60 秒。
What am I doing wrong, or did I misunderstand how the DateTime works.我做错了什么,或者我误解了 DateTime 的工作原理。
Thanks in advance提前致谢
instead of .Date
, try calling .ToLongDateString()
as in Debug.Log("In future date time "+inFutureDateTime.ToLongDateString())
而不是
.Date
,尝试调用.ToLongDateString()
,如Debug.Log("In future date time "+inFutureDateTime.ToLongDateString())
.Date
is a holder intended for Date only. .Date
是仅用于 Date 的持有人。
Unfortunately when converted to string it displays a time component as well.不幸的是,当转换为字符串时,它也会显示一个时间分量。
The default ToString, or one of it's overrides will display the full date time:默认 ToString 或其中一个覆盖将显示完整的日期时间:
Debug.Log("In future date time " + inFutureDateTime)
Date return component date not date format standard.日期返回组件日期不是日期格式标准。 Please see following approach:
请参阅以下方法:
DateTime inFutureDateTime = DateTime.Now.AddSeconds(60);
Debug.Log("In future date time " + inFutureDateTime.Date.ToLongDateString());
The origin of the problem is in the .Date
: it returns Date part of the initial DateTime
value (note, that time part is 0:0:0.000
).问题的根源在于
.Date
:它返回初始DateTime
值的Date部分(注意,该时间部分是0:0:0.000
)。 I suggest using string interpolation where you can specify text, variables, their formats, etc.我建议使用字符串插值,您可以在其中指定文本、变量、它们的格式等。
// Here we specify the required format - MM/dd/yyyy HH:mm:ss
Debug.Log($"In future date time {inFutureDateTime:MM/dd/yyyy HH:mm:ss}");
If you want to use the default format (from CultureInfo.CurrentCulture
):如果您想使用默认格式(来自
CultureInfo.CurrentCulture
):
Debug.Log($"In future date time {inFutureDateTime}");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.