Difference between System.DateTime.Now and System.DateTime.Today

后端 未结 8 1010
悲哀的现实
悲哀的现实 2020-11-28 19:23

Can anyone explain the difference between System.DateTime.Now and System.DateTime.Today in C#.NET? Pros and cons of each if possible.

相关标签:
8条回答
  • 2020-11-28 20:14

    I thought of Adding these links -

    • A brief History of DateTime - By Anthony Moore by BCL team
    • Choosing between Datetime and DateTime Offset - by MSDN
    • Do not forget SQL server 2008 onwards has a new Datatype as DateTimeOffset
    • The .NET Framework includes the DateTime, DateTimeOffset, and TimeZoneInfo types, all of which can be used to build applications that work with dates and times.
    • Performing Arithmetic Operations with Dates and Times-MSDN

    Coming back to original question , Using Reflector i have explained the difference in code

     public static DateTime Today
        {
          get
          {
            return DateTime.Now.Date;   // It returns the date part of Now
    
            //Date Property
           // returns same date as this instance, and the time value set to 12:00:00 midnight (00:00:00) 
          }
        }
    
    
        private const long TicksPerMillisecond = 10000L;
        private const long TicksPerDay = 864000000000L;
        private const int MillisPerDay = 86400000;
    
        public DateTime Date
        {
           get
          {
            long internalTicks = this.InternalTicks; // Date this instance is converted to Ticks 
            return new DateTime((ulong) (internalTicks - internalTicks % 864000000000L) | this.InternalKind);  
    // Modulo of TicksPerDay is subtracted - which brings the time to Midnight time 
          }
        }
    
    
         public static DateTime Now
            {
              get
              {
               /* this is why I guess Jon Skeet is recommending to use  UtcNow as you can see in one of the above comment*/
                DateTime utcNow = DateTime.UtcNow;
    
    
                /* After this i guess it is Timezone conversion */
                bool isAmbiguousLocalDst = false;
                long ticks1 = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utcNow, out isAmbiguousLocalDst).Ticks;
                long ticks2 = utcNow.Ticks + ticks1;
                if (ticks2 > 3155378975999999999L)
                  return new DateTime(3155378975999999999L, DateTimeKind.Local);
                if (ticks2 < 0L)
                  return new DateTime(0L, DateTimeKind.Local);
                else
                  return new DateTime(ticks2, DateTimeKind.Local, isAmbiguousLocalDst);
              }
            }
    
    0 讨论(0)
  • 2020-11-28 20:15
    DateTime dt = new DateTime();// gives 01/01/0001 12:00:00 AM
    DateTime dt = DateTime.Now;// gives today date with current time
    DateTime dt = DateTime.Today;// gives today date and 12:00:00 AM time
    
    0 讨论(0)
提交回复
热议问题