C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: We see the "now" variable being assigned to DateTime.Now. This variable contains the timestamp of the current DateTime.
WriteLine: When you pass the "now" local to Console.WriteLine, it will be printed to the screen.
ConsoleTip: The final lines of the example use the collection initializer syntax to set the HiringDate property to the DateTime.Now value.
C# program that uses DateTime.Now
using System;
class Program
{
class Employee
{
public DateTime HiringDate { get; set; }
}
static void Main()
{
// Write the current date and time.
// ... Access DateTime.Now.
DateTime now = DateTime.Now;
Console.WriteLine("NOW: " + now);
// Store a DateTime in a class.
// ... It no longer will be "now" as it is just a value in memory.
Employee employee = new Employee() { HiringDate = now };
Console.WriteLine("HIRING DATE: " + employee.HiringDate);
}
}
Output
NOW: 8/7/2019 10:37:05 AM
HIRING DATE: 8/7/2019 10:37:05 AM
And: Your local variable will remain constant unless you reassign it. Its value will not change in any other way.
Here: We pause (using Thread.Sleep) between assigning a local DateTime and then displaying it again. The values printed are the same.
SleepC# program that assigns to DateTime.Now
using System;
class Program
{
static void Main()
{
DateTime now = DateTime.Now; // <-- Value is copied into local
Console.WriteLine(now);
System.Threading.Thread.Sleep(10000);
//
// This variable has the same value as before.
//
Console.WriteLine(now);
}
}
Output
2/25/2011 11:12:13 AM
Therefore: Some experts regard DateTime.Now as a mistake. Please see the book CLR via C# (Second Edition) by Jeffrey Richter.