1

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

Community
  • 1
  • 1
Dimitroff
  • 120
  • 1
  • 7
  • It is a static property so it requires no instance. https://msdn.microsoft.com/en-us/library/system.datetime.now%28v=vs.110%29.aspx – Travis J Mar 20 '15 at 20:55
  • This should help you understand what is going on https://msdn.microsoft.com/en-us/library/system.datetime%28v=vs.110%29.aspx – BRBT Mar 20 '15 at 20:57

2 Answers2

6

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

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.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117