简体   繁体   English

DateTime现在是什么= DateTime.Now; 用C#做?

[英]What does DateTime now = DateTime.Now; do in C#?

I found out how to get the current date and time as variables (right?) in C# thanks to this thread with the code 多亏了这个带有代码的线程 ,我才知道如何在C#中获取当前日期和时间作为变量(对吗?)。

DateTime now = DateTime.Now;
string date = now.GetDateTimeFormats('d')[0];
string time = now.GetDateTimeFormats('t')[0];

However I'm not sure what the first line does. 但是我不确定第一行做什么。 After some thinking I suppose it calls the current date and time data from the computer and applies/tells it to the program. 经过一番思考,我想它会从计算机中调用当前日期和时间数据,并将其应用/告知程序。

By the way, I'm a noob at programming and new to C#. 顺便说一下,我是编程新手,对C#还是陌生的。

The first line 第一行

DateTime now = DateTime.Now;

takes the current time, and stores it in a variable. 花费当前时间,并将其存储在变量中。 The reason it's done is to make sure that subsequent calls of GetDateTimeFormats are performed on a variable representing the same time. 这样做的原因是确保对表示相同时间的变量执行GetDateTimeFormats后续调用。 If you call DateTime.Now several times, you may get a different time each time that you make a call. 如果您多次调用DateTime.Now ,则每次拨打电话的时间可能会有所不同。

For example, if you do 例如,如果您这样做

string date = DateTime.Now.GetDateTimeFormats('d')[0];
string time = DateTime.Now.GetDateTimeFormats('t')[0];

very close to midnight, the date and time portions may belong to different dates. 非常接近午夜, datetime部分可能属于不同的日期。

Yes, it does exactly what you think it does. 是的,它完全按照您的想法去做。

You created a variable called now (type DateTime ) and assigned it to DateTime.Now which is a special static property of DateTime that: 您创建了一个名为变量now (类型DateTime ),并赋予它DateTime.Now这是一个特殊的静态属性DateTime是:

Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time. 获取一个DateTime对象,该对象设置为此计算机上的当前日期和时间,表示为本地时间。

( MSDN ) MSDN

So you have the date and time that line of code was run stored off in the now variable. 因此,您可以将运行代码行的日期和时间存储在now变量中。 Simple as that. 就那么简单。

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

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