简体   繁体   中英

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

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#.

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. If you call DateTime.Now several times, you may get a different time each time that you make a call.

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.

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:

Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time.

( MSDN )

So you have the date and time that line of code was run stored off in the now variable. Simple as that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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