HomeSearch

VB.NET DateTime.Now Property (Today)

Use the DateTime.Now Property to get the current time. Compare Now with Today.

DateTime.Now. With this property we get a copy of a Structure that stores the current time. We demonstrate DateTime.Now and show how it changes when accessed at a later time.DateTime

Now changes when called the same way at different points in time. It has no side effects. For optimization, consider caching the result of DateTime.Now.

An example. When we assign to DateTime.Now, the current time is copied to a storage location. This means that the time stored will never change after that point.

Step 1: When you access DateTime.Now, the current time is computed. This is stored in a Structure.

Step 2: The Sleep call causes 10 seconds to pass. So the current time has changed.

Sleep

Step 3: The second DateTime returned by Now is 10 seconds later. The value returned by Now keeps changing.

VB.NET program that uses DateTime.Now Module Module1 Sub Main() ' Step 1: load now into local variable. Dim now As DateTime = DateTime.Now Console.WriteLine(now) ' Step 2: sleep 10 seconds. Threading.Thread.Sleep(10000) ' Step 3: use property again. Console.WriteLine(DateTime.Now) End Sub End Module Output 2/3/2020 4:25:30 AM 2/3/2020 4:25:40 AM

Today. Here we compare the result of DateTime.Now with DateTime.Today. The Today property is the same as Now, but with the time stripped.

So: We can use Today instead of Now when we do not want the time part of the DateTime structure.

VB.NET program that uses DateTime.Today Module Module1 Sub Main() Console.WriteLine("NOW: {0}", DateTime.Now) Console.WriteLine("TODAY: {0}", DateTime.Today) End Sub End Module Output NOW: 2/3/2020 4:33:38 AM TODAY: 2/3/2020 12:00:00 AM

A summary. DateTime.Now can be stored in a local variable. The value of "Now" changes with time. Conceptually DateTime.Now acts as a method that returns the current time.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.