Difference Between System.Datetime.Now and System.Datetime.Today

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

DateTime.Now returns a DateTime value that consists of the local date and time of the computer where the code is running. It has DateTimeKind.Local assigned to its Kind property. It is equivalent to calling any of the following:

  • DateTime.UtcNow.ToLocalTime()
  • DateTimeOffset.UtcNow.LocalDateTime
  • DateTimeOffset.Now.LocalDateTime
  • TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Local)
  • TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.Local)

DateTime.Today returns a DateTime value that has the same year, month, and day components as any of the above expressions, but with the time components set to zero. It also has DateTimeKind.Local in its Kind property. It is equivalent to any of the following:

  • DateTime.Now.Date
  • DateTime.UtcNow.ToLocalTime().Date
  • DateTimeOffset.UtcNow.LocalDateTime.Date
  • DateTimeOffset.Now.LocalDateTime.Date
  • TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Local).Date
  • TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.Local).Date

Note that internally, the system clock is in terms of UTC, so when you call DateTime.Now it first gets the UTC time (via the GetSystemTimeAsFileTime function in the Win32 API) and then it converts the value to the local time zone. (Therefore DateTime.Now.ToUniversalTime() is more expensive than DateTime.UtcNow.)

Also note that DateTimeOffset.Now.DateTime will have similar values to DateTime.Now, but it will have DateTimeKind.Unspecified rather than DateTimeKind.Local - which could lead to other errors depending on what you do with it.

So, the simple answer is that DateTime.Today is equivalent to DateTime.Now.Date.

But IMHO - You shouldn't use either one of these, or any of the above equivalents.

When you ask for DateTime.Now, you are asking for the value of the local calendar clock of the computer that the code is running on. But what you get back does not have any information about that clock! The best that you get is that DateTime.Now.Kind == DateTimeKind.Local. But whose local is it? That information gets lost as soon as you do anything with the value, such as store it in a database, display it on screen, or transmit it using a web service.

If your local time zone follows any daylight savings rules, you do not get that information back from DateTime.Now. In ambiguous times, such as during a "fall-back" transition, you won't know which of the two possible moments correspond to the value you retrieved with DateTime.Now. For example, say your system time zone is set to Mountain Time (US & Canada) and you ask for DateTime.Now in the early hours of November 3rd, 2013. What does the result 2013-11-03 01:00:00 mean? There are two moments of instantaneous time represented by this same calendar datetime. If I were to send this value to someone else, they would have no idea which one I meant. Especially if they are in a time zone where the rules are different.

The best thing you could do would be to use DateTimeOffset instead:

// This will always be unambiguous.
DateTimeOffset now = DateTimeOffset.Now;

Now for the same scenario I described above, I get the value 2013-11-03 01:00:00 -0600 before the transition, or 2013-11-03 01:00:00 -0700 after the transition. Anyone looking at these values can tell what I meant.

I wrote a blog post on this very subject. Please read - The Case Against DateTime.Now.

Also, there are some places in this world (such as Brazil) where the "spring-forward" transition happens exactly at Midnight. The clocks go from 23:59 to 01:00. This means that the value you get for DateTime.Today on that date, does not exist! Even if you use DateTimeOffset.Now.Date, you are getting the same result, and you still have this problem. It is because traditionally, there has been no such thing as a Date object in .Net. So regardless of how you obtain the value, once you strip off the time - you have to remember that it doesn't really represent "midnight", even though that's the value you're working with.

If you really want a fully correct solution to this problem, the best approach is to use NodaTime. The LocalDate class properly represents a date without a time. You can get the current date for any time zone, including the local system time zone:

using NodaTime;
...

Instant now = SystemClock.Instance.Now;

DateTimeZone zone1 = DateTimeZoneProviders.Tzdb.GetSystemDefault();
LocalDate todayInTheSystemZone = now.InZone(zone1).Date;

DateTimeZone zone2 = DateTimeZoneProviders.Tzdb["America/New_York"];
LocalDate todayInTheOtherZone = now.InZone(zone2).Date;

If you don't want to use Noda Time, there is now another option. I've contributed an implementation of a date-only object to the .Net CoreFX Lab project. You can find the System.Time package object in their MyGet feed. Once added to your project, you will find you can do any of the following:

using System;
...

Date localDate = Date.Today;

Date utcDate = Date.UtcToday;

Date tzSpecificDate = Date.TodayInTimeZone(anyTimeZoneInfoObject);

What is the difference between datetime.now() and datetime.today() in Python

DateTime.Today only gives today's date and default time as 12:00:00.

DateTime.Today : 1/1/2018 12:00:00 AM.

DateTime.Now gives current time of running thread with today's date. (Date and Time of the computer where code is running)

DateTime.Now : 1/1/2018 8:49:52 AM.

DateTime.Now vs. DateTime.UtcNow

DateTime.UtcNow tells you the date and time as it would be in Coordinated Universal Time, which is also called the Greenwich Mean Time time zone - basically like it would be if you were in London England, but not during the summer. DateTime.Now gives the date and time as it would appear to someone in your current locale.

I'd recommend using DateTime.Now whenever you're displaying a date to a human being - that way they're comfortable with the value they see - it's something that they can easily compare to what they see on their watch or clock. Use DateTime.UtcNow when you want to store dates or use them for later calculations that way (in a client-server model) your calculations don't become confused by clients in different time zones from your server or from each other.

Why does System.DateTime.Now work when the application is ran on my computer but does not work when i start the application over workgroup?

The "d" format string uses the system-level configured short date string format. Individuals can change this format on their system as they see fit. Therefore, if you need to rely on the result looking a certain way, you should not use the "d" format string.

Instead, you may be tempted to do this:

void Start()
{
DateTime today = DateTime.Now;
string[] day = today.ToString("dd/MM/yyyy").Split('/');
text.text = $"{day[1]}.{day[0]}.{day[2]}";
}

But this is also not quite correct. In .Net date format strings, the / character has special meaning, where it stands in place of the system date separator. Again, this value might be different from what you expect based on the cultural or custom settings present in the OS.

What you should really do is this:

void Start()
{
text.text = DateTime.Now.ToString("d.M.yyyy");
}

This will always provide the expected value (though I had to guess on the day format, whether or not you expect to ever see a leading 0 at the beginning of the month), and it will save you some memory allocations creating the array and intermediate string.

Difference between System.DateTime and System.DateTimeOffset

A DateTime value defines a particular date and time, it includes a Kind property that provides limited information about the time zone to which that date and time belongs.

The DateTimeOffset structure represents a date and time value, together with an offset that indicates how much that value differs from UTC. Thus, the value always unambiguously identifies a single point in time.

DateTimeOffset should be considered the default date and time type for application development as the uses for DateTimeOffset values are much more common than those for DateTime values.

See more info, code examples at:
http://msdn.microsoft.com/en-us/library/bb384267.aspx

System.DateTime? vs System.DateTime

? means that the type is nullable. For details, see e.g. MSDN

Nullable is a compiler-supported wrapper around value types that allows value types to become null.

To access the DateTime value, you need to do the following:

DateTime? dateOrNull = myCalendarExtender.SelectedDate;
if (dateOrNull != null)
{
DateTime newSelectedDate = dateOrNull.Value;
}

What does System.DateTime.Now return in C#?

DateTime.Now performs a few steps:

  • Get UTC time from the OS
  • Get timezone info from the registry of the machine on which it is executing
  • Use that timezone information to resolve UTC to local time (again, local to the executing machine)

If this returns Client time, how to get Server time and vice-versa?

If you are dealing with clients in multiple timezones, it's often useful to store all dates in UTC and then store the client's timezone for conversion purposes.

JavaScript can also be useful for resolving UTC dates to client time and/or for obtaining time in the web browser.

Geolocation (e.g. examining the user's IP) can also be used to make a guess as to the user's location/timezone, though it's not guaranteed to be accurate.

Why DateTime.Now and DateTime.UtcNow Isn't My Current Local DateTime?

Make sure you are not manipulating the timezone somewhere in code, or playing with System.Globalization.CultureInfo

Try to search in all your source code for System.Globalization.CultureInfo may be it is somewhere, also may be the time zone is cached somewhere so try to call System.Globalization.CultureInfo.CurrentCulture.ClearCachedData() before DateTime.Now

.NET DateTime.Now returns incorrect time when time zone is changed



Related Topics



Leave a reply



Submit