Sorry if this seems as a stupid question, but I cannot find an answer anywhere and I am a bit of a newbie. DateTime shows to be what I surmised as the Min Date. For instance:
DateTime updatedDate = new DateTime();
outItem.AddDate = updatedDate.ToLongDateString();
The output comes out to January 01, 0001. I've tried many variations of this with similar results. What am I doing wrong?
It depends on what you mean by "wrong". new DateTime() does indeed have the same value as DateTime.MinValue. If you want the current time, you should use:
DateTime updatedDate = DateTime.Now;
or
DateTime updatedDate = DateTime.UtcNow;
(The first gives you the local time, the second gives you the universal time. DateTime is somewhat messed up when it comes to the local/universal divide.)
If you're looking to get the current date, use DateTime.Now. You're creating a new instance of the date class, and the min value is its default value.
DateTime updatedDate = DateTime.Now;
outItem.AddDate = updatedDate.ToLongDateString();
EDIT: Actually, you can shorten your code by just doing this:
outItem.AddDate = DateTime.Now.ToLongDateString();
Jon Skeet says correct, and I have some to add.
The "wrong" depends on what time you want to get.
The DateTime is a struct, and the the default contructor of a struct
always initializes all fields to their zero for numeric type and null
for reference type.
so if you want to get the current local date and time, you can call static property DateTime.Now.
var curDateTime = DateTime.Now;
if you want to get UTC time.
var utcDateTime = DateTime.UtcNow;
Note: the DateTime.UtcNow get the current date and time, but instead of using local time zone, it uses UTC time instead.
You can reference the link as below.
http://blackrabbitcoder.net/archive/2010/11/18/c.net-little-wonders-datetime-is-packed-with-goodies.aspx
Related
I have following date time format
TimeZoneDetails.TimeZoneInstance ="Australia/Perth"
DateTime Today = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow,TimeZoneDetails.TimeZoneInstance);
Does today variable store the date based on timezone?
string date = "2020-03-19";
DateTime startdate = DateTime.Parse(date);
What is the timezone of startdate variable?
DateTime enddate = TimeZoneInfo.ConvertTimeToUtc(startdate, TimeZoneDetails.TimeZoneInstance);
Will enddate variable converted to UTC time?
A few things:
"Australia/Perth" is an IANA time zone identifier. It will work with .NET on Linux or Mac OSX, but on Windows you'd have to use "W. Australia Standard Time" instead. Alternatively, you could use my TimeZoneConverter library to work with either form of identifier on any platform.
In your code:
TimeZoneDetails.TimeZoneInstance ="Australia/Perth"
This isn't generally valid. Given the usage in the rest of your code, your TimeZoneInstance would have to be a TimeZoneInfo object. You can't assign a string in that way. You'd have to use a function like TimeZoneInfo.FindSystemTimeZoneById, or TZConvert.GetTimeZoneInfo from TimeZoneConverter, or a similar function in your own code. (Also you're missing a semicolon.)
In your code:
string date = "2020-03-19";
DateTime startdate = DateTime.Parse(date);
You asked what the time zone is in the startdate variable. That's a DateTime, which does not store time zone or offset information. It only has a .Kind property, which is of type DateTimeKind. In your example, it will be DateTimeKind.Unspecified. Also note the time will be set to 00:00:00.0000000.
You can read more about this in the documentation, here and here.
In your code:
DateTime enddate = TimeZoneInfo.ConvertTimeToUtc(startdate, TimeZoneDetails.TimeZoneInstance);
Yes, that will correctly convert the DateTime from the time zone given to UTC. Because startdate.Kind == DateTimeKind.Unspecified, the value is treated as belonging to the time zone specified. The resulting value will have enddate.Kind == DateTimeKind.Utc.
You can read more in the documentation, here.
In comments you asked:
which one is default for DateTimeKind?
That depends on which method you call to create the DateTime, and what values you pass in. In your case, because you call DateTime.Parse and pass a string that contains no time zone offset information, the resulting value has .Kind == DateTimeKind.Unspecified. You can read more about the behavior of DateTime.Parse in the remarks section here. Other methods and constructors behave similarly, but you should check the documentation for each, or validate the results yourself. You may find conversion errors if you, for example, think a DateTime has Unspecified kind, but it actually has Local kind due to how you obtain it.
I have already seen this.
I am going to get only Date from a DateTime variable and in this way I used this code:
DateTime Start = GetaDateTime();
String Day = Start.ToString("yyyy/MM/dd");
DateTime d = Convert.ToDateTime(Day);
But when I use d.Date it gives me '2014-08-23 12:00 AM'
Actually I should not get 12:00AM any more????
Actually I should not get 12:00AM any more????
Why not? A DateTime has no notion of whether it's meant to be a date or a date and time, or any sort of string formatting. It's just a point in time (and not even quite that, given the odd Kind part of it).
Note that a simpler way of getting a DateTime which is the same as another but at midnight is just to use Date to start with:
DateTime start = Foo();
DateTime date = start.Date;
No need for formatting and then parsing.
There's no .NET type representing just a date. For that, you'll want something like my Noda Time project, which has a rather richer set of date/time types to play with.
I have the following code in my C# program.
DateTime dateForButton = DateTime.Now;
dateForButton = dateForButton.AddDays(-1); // ERROR: un-representable DateTime
Whenever I run it, I get the following error:
The added or subtracted value results in an un-representable DateTime.
Parameter name: value
Iv'e never seen this error message before, and don't understand why I'm seeing it. From the answers Iv'e read so far, I'm lead to believe that I can use -1 in an add operation to subtract days, but as my question shows this is not the case for what I'm attempting to do.
DateTime dateForButton = DateTime.Now.AddDays(-1);
That error usually occurs when you try to subtract an interval from DateTime.MinValue or you want to add something to DateTime.MaxValue (or you try to instantiate a date outside this min-max interval). Are you sure you're not assigning MinValue somewhere?
You can do:
DateTime.Today.AddDays(-1)
You can use the following code:
dateForButton = dateForButton.Subtract(TimeSpan.FromDays(1));
The dateTime.AddDays(-1) does not subtract that one day from the dateTime reference. It will return a new instance, with that one day subtracted from the original reference.
DateTime dateTime = DateTime.Now;
DateTime otherDateTime = dateTime.AddDays(-1);
Instead of directly decreasing number of days from the date object directly, first get date value then subtract days. See below example:
DateTime SevenDaysFromEndDate = someDate.Value.AddDays(-1);
Here, someDate is a variable of type DateTime.
The object (i.e. destination variable) for the AddDays method can't be the same as the source.
Instead of:
DateTime today = DateTime.Today;
today.AddDays(-7);
Try this instead:
DateTime today = DateTime.Today;
DateTime sevenDaysEarlier = today.AddDays(-7);
I've had issues using AddDays(-1).
My solution is TimeSpan.
DateTime.Now - TimeSpan.FromDays(1);
Using AddDays(-1) worked for me until I tried to cross months. When I tried to subtract 2 days from 2017-01-01 the result was 2016-00-30. It could not handle the month change correctly (though the year seemed to be fine).
I used date = Convert.ToDateTime(date).Subtract(TimeSpan.FromDays(2)).ToString("yyyy-mm-dd");
and have no issues.
Can anyone explain the difference between System.DateTime.Now and System.DateTime.Today in C#.NET? Pros and cons of each if possible.
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);
Time. .Now includes the 09:23:12 or whatever; .Today is the date-part only (at 00:00:00 on that day).
So use .Now if you want to include the time, and .Today if you just want the date!
.Today is essentially the same as .Now.Date
The DateTime.Now property returns the current date and time, for example 2011-07-01 10:09.45310.
The DateTime.Today property returns the current date with the time compnents set to zero, for example 2011-07-01 00:00.00000.
The DateTime.Today property actually is implemented to return DateTime.Now.Date:
public static DateTime Today {
get {
DateTime now = DateTime.Now;
return now.Date;
}
}
DateTime.Today represents the current system date with the time part set to 00:00:00
and
DateTime.Now represents the current system date and time
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);
}
}
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
DateTime.Today is DateTime.Now with time set to zero.
It is important to note that there is a difference between a DateTime value, which represents the number of ticks that have elapsed since midnight of January 1, 0000, and the string representation of that DateTime value, which expresses a date and time value in a culture-specific-specific format:
https://msdn.microsoft.com/en-us/library/system.datetime.now%28v=vs.110%29.aspx
DateTime.Now.Ticks is the actual time stored by .net (essentially UTC time), the rest are just representations (which are important for display purposes).
If the Kind property is DateTimeKind.Local it implicitly includes the time zone information of the local computer. When sending over a .net web service, DateTime values are by default serialized with time zone information included, e.g. 2008-10-31T15:07:38.6875000-05:00, and a computer in another time zone can still exactly know what time is being referred to.
So, using DateTime.Now and DateTime.Today is perfectly OK.
You usually start running into trouble when you begin confusing the string representation with the actual value and try to "fix" the DateTime, when it isn't broken.
DateTime.Now.ToShortDateString() will display only the date part
Current project: To make a time program in C# with two classes Time and ExtendedTime Time is just the normal time and ExtendedTime has the time zone.
When you start the program I need to click a button and get the current time but there is an option to change the time zone. This in turn changes the time and also has an option to increment the time by so many hours and or minutes.
Currently, this is what my displayTime method in the Time class looks like:
public virtual string displayTime()
{
DateTime time = DateTime.Now; // Use current time
string format = "MMM ddd d HH:mm yyyy"; // Use this format
MessageBox.Show(time.ToString(format)); // Write to console
return time.ToString(format);
}//end of displayTime
Which isn't bad except that everytime I call it NO MATTER WHAT it will always tell me the current time because of DateTime.Now
I'm not totally sure how to get around that. I'm sure there is a one time deal i can do to do this but not sure of the syntax.
You can use the TimeSpan class to manipulate the DateTime class. For example:
DateTime now = DateTime.Now;
DateTime twoHoursLater = now + new TimeSpan(2,0,0);
DateTime twoDaysLater = now + new TimeSpan(2,0,0,0);
If you're using a user-supplied time, such as one from a textbox, you can use
DateTime userSuppliedTime = DateTime.Parse(myTextbox.Text);
Which will give you a DateTime that corresponds to whatever the user enters. Be warned, however, that if the user types in something that the system does not recognize as valid, this will throw an exception.
DateTime.Add and DateTime.Subtract should suffice.
DateTime adjusted = DateTime.Now.Add(TimeSpan.FromMinutes(30));
You get current time became you have no code that manipulates that DateTime field.
To apply time zones, look into TimeZoneInfo class.
You really should look into using the DateTimeOffset structure, which works well for this kind of thing.