DateTime.AddDays vs Calendar.AddDays - c#

What is the difference between DateTime.AddDays and Calendar.AddDays?
Is DateTime type calendar independent?

DateTime.AddDays just converts days to ticks and adds this number of ticks to the date time. The default implementation of Calendar.AddDays does exactly the same. However, since it is a virtual method it can be implemented in specific calendar in a more complicated way, e.g. something like here: http://codeblog.jonskeet.uk/2010/12/01/the-joys-of-date-time-arithmetic/

I believe that DateTime is hard-coded to use the Gregorian calendar, effectively.
For example, if you look at DateTime.DaysInMonth it assumes there are 12 months, whereas the HebrewCalendar supports 13.
EDIT: There are some aspects of DateTime which do accommodate other calendars, such as this constructor. However, I believe it just converts it to a Gregorian calendar:
Calendar calendar = new HebrewCalendar();
DateTime dt = new DateTime(5901, 13, 1, 0, 0, 0, calendar); // Uses month 13!
Console.WriteLine(dt.Year); // 2141
Console.WriteLine(dt.Month); // 9

As far as I know the Calendar.AddDays method returns a DateTime object and calls it's function.

The answer to this question is extremely easy to answer. There is no difference between the two functions.
Calendar.AddDays is also a DateTime
DateTime does not extend that particular functionality the only thing it uses is UTC and Local time. One should also suggest that a Calendar is NOT a DateTime object, it might not behave the same, and does not appear to provide a method to get the current system time.
Edit - I originally thought you were talking about the Web Control, this appears to be a globalization, to allow you to display the current date and time for a given user base do their declared operating system's settings.

Related

Is there functionality to convert from UTC time to local time using country name? [duplicate]

We are developing a C# application for a web-service client. This will run on Windows XP PC's.
One of the fields returned by the web service is a DateTime field. The server returns a field in GMT format i.e. with a "Z" at the end.
However, we found that .NET seems to do some kind of implicit conversion and the time was always 12 hours out.
The following code sample resolves this to some extent in that the 12 hour difference has gone but it makes no allowance for NZ daylight saving.
CultureInfo ci = new CultureInfo("en-NZ");
string date = "Web service date".ToString("R", ci);
DateTime convertedDate = DateTime.Parse(date);
As per this date site:
UTC/GMT Offset
Standard time zone: UTC/GMT +12 hours
Daylight saving time: +1 hour
Current time zone offset: UTC/GMT +13 hours
How do we adjust for the extra hour? Can this be done programmatically or is this some kind of setting on the PC's?
For strings such as 2012-09-19 01:27:30.000, DateTime.Parse cannot tell what time zone the date and time are from.
DateTime has a Kind property, which can have one of three time zone options:
Unspecified
Local
Utc
NOTE If you are wishing to represent a date/time other than UTC or your local time zone, then you should use DateTimeOffset.
So for the code in your question:
DateTime convertedDate = DateTime.Parse(dateStr);
var kind = convertedDate.Kind; // will equal DateTimeKind.Unspecified
You say you know what kind it is, so tell it.
DateTime convertedDate = DateTime.SpecifyKind(
DateTime.Parse(dateStr),
DateTimeKind.Utc);
var kind = convertedDate.Kind; // will equal DateTimeKind.Utc
Now, once the system knows its in UTC time, you can just call ToLocalTime:
DateTime dt = convertedDate.ToLocalTime();
This will give you the result you require.
I'd look into using the System.TimeZoneInfo class if you are in .NET 3.5. See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx. This should take into account the daylight savings changes correctly.
// Coordinated Universal Time string from
// DateTime.Now.ToUniversalTime().ToString("u");
string date = "2009-02-25 16:13:00Z";
// Local .NET timeZone.
DateTime localDateTime = DateTime.Parse(date);
DateTime utcDateTime = localDateTime.ToUniversalTime();
// ID from:
// "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zone"
// See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.id.aspx
string nzTimeZoneKey = "New Zealand Standard Time";
TimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(nzTimeZoneKey);
DateTime nzDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, nzTimeZone);
TimeZone.CurrentTimeZone.ToLocalTime(date);
DateTime objects have the Kind of Unspecified by default, which for the purposes of ToLocalTime is assumed to be UTC.
To get the local time of an Unspecified DateTime object, you therefore just need to do this:
convertedDate.ToLocalTime();
The step of changing the Kind of the DateTime from Unspecified to UTC is unnecessary. Unspecified is assumed to be UTC for the purposes of ToLocalTime: http://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime.aspx
I know this is an older question, but I ran into a similar situation, and I wanted to share what I had found for future searchers, possibly including myself :).
DateTime.Parse() can be tricky -- see here for example.
If the DateTime is coming from a Web service or some other source with a known format, you might want to consider something like
DateTime.ParseExact(dateString,
"MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)
or, even better,
DateTime.TryParseExact(...)
The AssumeUniversal flag tells the parser that the date/time is already UTC; the combination of AssumeUniversal and AdjustToUniversal tells it not to convert the result to "local" time, which it will try to do by default. (I personally try to deal exclusively with UTC in the business / application / service layer(s) anyway. But bypassing the conversion to local time also speeds things up -- by 50% or more in my tests, see below.)
Here's what we were doing before:
DateTime.Parse(dateString, new CultureInfo("en-US"))
We had profiled the app and found that the DateTime.Parse represented a significant percentage of CPU usage. (Incidentally, the CultureInfo constructor was not a significant contributor to CPU usage.)
So I set up a console app to parse a date/time string 10000 times in a variety of ways. Bottom line:
Parse() 10 sec
ParseExact() (converting to local) 20-45 ms
ParseExact() (not converting to local) 10-15 ms
... and yes, the results for Parse() are in seconds, whereas the others are in milliseconds.
I'd just like to add a general note of caution.
If all you are doing is getting the current time from the computer's internal clock to put a date/time on the display or a report, then all is well. But if you are saving the date/time information for later reference or are computing date/times, beware!
Let's say you determine that a cruise ship arrived in Honolulu on 20 Dec 2007 at 15:00 UTC. And you want to know what local time that was.
1. There are probably at least three 'locals' involved. Local may mean Honolulu, or it may mean where your computer is located, or it may mean the location where your customer is located.
2. If you use the built-in functions to do the conversion, it will probably be wrong. This is because daylight savings time is (probably) currently in effect on your computer, but was NOT in effect in December. But Windows does not know this... all it has is one flag to determine if daylight savings time is currently in effect. And if it is currently in effect, then it will happily add an hour even to a date in December.
3. Daylight savings time is implemented differently (or not at all) in various political subdivisions. Don't think that just because your country changes on a specific date, that other countries will too.
#TimeZoneInfo.ConvertTimeFromUtc(timeUtc, TimeZoneInfo.Local)
Don't forget if you already have a DateTime object and are not sure if it's UTC or Local, it's easy enough to use the methods on the object directly:
DateTime convertedDate = DateTime.Parse(date);
DateTime localDate = convertedDate.ToLocalTime();
How do we adjust for the extra hour?
Unless specified .net will use the local pc settings. I'd have a read of: http://msdn.microsoft.com/en-us/library/system.globalization.daylighttime.aspx
By the looks the code might look something like:
DaylightTime daylight = TimeZone.CurrentTimeZone.GetDaylightChanges( year );
And as mentioned above double check what timezone setting your server is on. There are articles on the net for how to safely affect the changes in IIS.
In answer to Dana's suggestion:
The code sample now looks like:
string date = "Web service date"..ToString("R", ci);
DateTime convertedDate = DateTime.Parse(date);
DateTime dt = TimeZone.CurrentTimeZone.ToLocalTime(convertedDate);
The original date was 20/08/08; the kind was UTC.
Both "convertedDate" and "dt" are the same:
21/08/08 10:00:26; the kind was local
I had the problem with it being in a data set being pushed across the wire (webservice to client) that it would automatically change because the DataColumn's DateType field was set to local. Make sure you check what the DateType is if your pushing DataSets across.
If you don't want it to change, set it to Unspecified
I came across this question as I was having a problem with the UTC dates you get back through the twitter API (created_at field on a status); I need to convert them to DateTime. None of the answers/ code samples in the answers on this page were sufficient to stop me getting a "String was not recognized as a valid DateTime" error (but it's the closest I have got to finding the correct answer on SO)
Posting this link here in case this helps someone else - the answer I needed was found on this blog post: http://www.wduffy.co.uk/blog/parsing-dates-when-aspnets-datetimeparse-doesnt-work/ - basically use DateTime.ParseExact with a format string instead of DateTime.Parse
This code block uses universal time to convert current DateTime object then converts it back to local DateTime. Works perfect for me I hope it helps!
CreatedDate.ToUniversalTime().ToLocalTime();

Comparing time regardless of date

I have an object that has properties currently as DateTime.
The object is marked as valid within a time frame. The default being 00:00:00 to 23:59:59
The user enters the value in the UI and the property is set via:
new DateTime(DateTime.Now.Year,
DateTime.Now.Month,
DateTime.Now.Day,
model.Hours,
model.Minutes,
model.Seconds)
This is then converted to UTC when it hits the database.
Today's date is 29th August 2013. If a colleague in India runs this program it will store the data in the database as 28th August 2013 18:30:00 as they are 5.5 hours ahead of UTC so 29th August 2013 00:00:00 becomes yesterday.
When the logic tries to determine if the object is valid the logic is:
if (DateTime.UtcNow.TimeOfDay > model.MyPropertyFromDB.TimeOfDay)
We are trying to determine if the current time is within a range of 00:00:00 and 23:59:59
This fails as 14:00 (current time) is not greater than 18:30
What would be the best approach to compare just times?
Would storing the values as DateTimeOffSet help, is using ToLocal() ok?
Other considerations are that a user in India is using the app which is hosted in the UK so it needs to be timezone aware.
Thanks
Like others, I'm still unclear on exactly what you are wanting. But clearly, you shouldn't do this:
new DateTime(DateTime.Now.Year,
DateTime.Now.Month,
DateTime.Now.Day,
model.Hours,
model.Minutes,
model.Seconds)
That would be much better as:
DateTime.Today.Add(new TimeSpan(model.Hours, model.Minutes, model.Seconds))
But why are you doing this to begin with? Either of these would give you back the local date. I assume this is going to run on a server, so do you really want the time zone of the server to influence this result? Probably not. Please read: The Case Against DateTime.Now.
If you wanted the UTC date, you could do this:
DateTime.UtcNow.Date.Add(new TimeSpan(model.Hours, model.Minutes, model.Seconds))
That would at least be universally the same regardless of your server's time zone. But still, I don't think this is what you are after.
What's not clear is why is the user only entering the time while you are assigning the current date. If the date is relevant, then shouldn't the user enter it and it would be part of your model?
If the date is not relevant, then why are you storing it? You can use a TimeSpan type for the time value internally. You didn't say what your database is, but let's just guess that it is SQL Server, in which case you could use the time type on the field in the table.
I suppose it's possible that the date is relevant, but you want to control it, while the user takes control of providing the time. If that's the case, then you must know the time zone of the user (or the time zone of whatever the context is if it's not the user). Assuming you had a Windows time zone identifier (see the timezone tag wiki), then you could do something like this:
var tz = TimeZoneInfo.FindSystemTimeZoneById(theTimeZoneId);
var local = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tz);
var dt = local.Date.Add(new TimeSpan(model.Hours, model.Minutes, model.Seconds));
If you don't have the time zone information, then this wouldn't be possible to solve.
As general advice, you might want to try using Noda Time instead of the built-in stuff. It's much better at helping you figure out this sort of thing. From the main page:
Noda Time is an alternative date and time API for .NET. It helps you to think about your data more clearly, and express operations on that data more precisely.
That appears to be directly the problem you are having here. If you want to clarify some of the questions I asked, I'd be happy to edit my answer and show you exactly how to do this with Noda Time.
Why your question is confusing
We are trying to determine if the current time is within a range of 00:00:00 and 23:59:59
All times are within that range. Well, maybe a value like 23:59:59.1 would be outside of it, but you aren't collecting fractional seconds in your model, so that's irrelevant. But why would you need to validate that? Maybe you are just trying to avoid numbers that aren't valid times at all? Like 99:99:99?
This fails as 14:00 (current time) is not greater than 18:30
Wait - you didn't say anything about comparing one time greater than another. 14:00 and 18:30 are both still in the range you specified.
What would be the best approach to compare just times?
Hard to answer. Are they both UTC times? Is one UTC and one is local? Are they both local? Do you know the time zone of the local times? Are you prepared to deal with ambiguous or invalid local times do to daylight saving time transitions?
Would storing the values as DateTimeOffSet help?
Perhaps, but you haven't given me enough information. It would help only if the date portion is relevant and the you get the correct offsets.
is using ToLocal() ok?
I would argue that no, it's not ok. Local in this context will give you the time zone of the server, which you probably don't want to introduce into your business logic.
So if I understand this correctly you have a time saved in UTC in the database and you are trying to determine whether it falls within a particular time frame? I'm not sure if you want the time frame in local time or UTC so here are both:
DateTime dbTime = model.MyPropertyFromDB;
TimeSpan minTime = new TimeSpan(0, 0, 0);
TimeSpan maxTime = new TimeSpan(23, 59, 59);
if (dbTime.TimeOfDay > minTime && dbTime.TimeOfDay < maxTime)
{
//Within time range (UTC)
}
if (dbTime.ToLocalTime().TimeOfDay > minTime && dbTime.ToLocalTime().TimeOfDay < maxTime)
{
//Within time range (local)
}
Edit: If you want to compare Now to a start and end time from an object in database:
TimeSpan now = DateTime.UtcNow.TimeOfDay;
TimeSpan startDate = model.startDate.TimeOfDay;
TimeSpan endDate = model.endDate.TimeOfDay;
if (now > startDate && now < endDate)
{
//Within time range (UTC)
}
I would say that the methodology being used here is fundamentally flawed and that you need to take a different approach.
new DateTime(DateTime.Now.Year, // Server date
DateTime.Now.Month,
DateTime.Now.Day,
model.Hours, // Local time
model.Minutes,
model.Seconds)
I can't see a way of 'normalising' the input in this way, unless you have a way of reliably knowing exactly which timezone a user is in. Simply, there's no easy way to turn a date built in this way into UTC.
My first question to you is, how is the model being passed from client to server? If you're using javascript/ajax then the solution should be fairly straightforward to solve by constructing the datetime object on the client (which will include their timezone data) and then rely on the browser to convert it to UTC for transit.
If you are using Razor\MVC then you can achieve a similar thing with forms encoding, except that you will need to call ToUTC on the server as the browser won't automatically fix the date for you for this media format.
Both methods require that you build a full datetime object on the client and then submit it, rather than trying to build it from seconds, minutes, hours on the server. You don't need to expose all this to the client of course, as long as the datetime is fully formed at the point of submission.
Once you've got a nice UTC datetime, you can extract just the time if you don't need the rest of it.
Hope this helps.
Pete

How to Use DateTime.Now function

Currently I am using DateTime.Now.ToLongDateString() to set a date property, although I would like to be more detailed in the date. The purpose is to perform a sort based on the date of an item, and this currently will give a date in the format Thursday, July 4, 2013. If several items have this same date property on the same day, the sort is not performed. Is there a function of DateTime.Now that will allow a date property with seconds?
To note, the day and year must still be included because the sort may happen over several days, in several years, but there may also be several instances of the item on the same day. What recommendation would you suggest, or is there a better way to go about this? Also, this must work for any culture and any time zone.
EDIT
In my MainPage I am populating a ListBox named Recent with a collection of pictures. From my Settings page, a user may choose ascending or descending sort order, and based on this the collection must be sorted accordingly before populating the listbox.
MainPage.xaml.cs
protected override void OnNavigatedTo(NavigationEventArgs e)
{
ObservableCollection<Selfie.Models.Picture> listItems = new ObservableCollection<Selfie.Models.Picture>(PictureRepository.Instance.Pictures);
if (Settings.AscendingSort.Value)
{
listItems.OrderBy(x => x.DateTaken);
Recent.ItemsSource = listItems;
}
else
{
listItems.OrderByDescending(x => x.DateTaken);
Recent.ItemsSource = listItems;
}
}
I have a class that Serializes and Deserializes the DateTime as a property of the Picture, which is applied to DateTaken, which I am trying to sort by.
EDIT 2
Okay,
you need to use the result of the OrderByDescending function.
// listItems remains unaffected.
var sorted = listItems.OrderByDescending();
Many functions, especially extensions that act upon structures with a level of immutablity, do not effect the source. The pure function should be used in a "fluent" style. The return value needs to be assinged to be utilized.
So, you need to do,
Recent.ItemsSource = listItems.OrderBy(x => x.DateTaken).ToList();
Its worth considering a tool like Resahrper to catch issues like this. They are common with the DateTime Add functions.
EDIT
Because you are working in a multi cultural situation, ensure that all your dates are instantiated and stored with a UTC kind, this is going to help you massively. Even if working in a single time-zone but sorting across Day light Saving Time boundries.
Instead of DateTime.Now use DateTime.UtcNow and leave all values as UTC DateTimes until they are exported or presented on the GUI.
This way you will be comparing apples with apples, and your sorting will work as expected and your data will be much easier to debug.
If you start to do anything sophisticated, you're going to find the cracks in .Nets DateTime implementation. It's considering using Jon Skeet and other's work on noda time which should overcome many pit falls.
This will not work across time zones, calendars or just Day light Saving
If you did need a sortable String for some reason, use DateTime.Now.ToString("o"); this makes a string with in the Round-trip format,
yyyy-MM-ddTHH:mm:ss.fffffff
which is nicely sortable, including a fractional portion. Assuming all the values come from the same timezone and calendar.
Just sort by DateTime.Now directly, without converting to a string. If you store the DateTime directly in your property, this will not be an issue.
The DateTime type supports dates and times down to the tick.
You can also format the date however you choose for display, but it is typically better to store, internally, the actual DateTime.
Just use the DateTime object directly. It will give you the day, month, year, hour, mins, seconds which is enough to do your sort.
For example: -
var foo = collection.OrderBy(d => d.Date);
The DateTime.Now.ToString() method will give you a string formatted with everything included.
But as #SimonBelanger pointed out, you should probably sort directly on the DateTime, not on the string representation.
If you need to serialize the date, as opposed to just sorting on the DateTime object, you can try converting it to unix time (the number of milliseconds since the start of the Unix Epoch).
stackoverflow.com/questions/9814060/...
Since it's just a long, you can sort it easily as well as storing it in a string or long or whatever.
If you can sort by the DateTime directly as Reed stated do that. However, if you can't, you'll want to string it out a very specific way. Maybe something like this:
date.ToString("YYYYMMddHHmmss")
because to sort dates in a character fashion you need to sort the parts of the date in the right order.
You can use DateTime.Now.ToString("YYYYMMddHHmmss") or DateTime.Now.Ticks
If you Add this piece of code DateTime.Now.ToString(); it will print 7/4/2013 10:05:18 PM ,
If you Add string time = DateTime.Now.ToString("hh-mm-ss"); it will print(10-07-36).
In the tostring method you can format the date based on your requirement.

Is this a correct use of DateTime? Will it work for all timezones?

So,
I'm storing a DateTime object as a private member on an object. This private member is set on object creation like so:
this.mCreateDate = DateTime.UtcNow.ToUniversalTime();
Now, later on in the application, I want to see how long the object has been alive for. This could be many weeks (this is a long running web app).
I'm getting the object lifetime like so:
DateTime now = DateTime.UtcNow.ToUniversalTime();
TimeSpan objectLifetime = now.Subtract(Foo.CreateDate);
// Output formatted time span
Does this all look correct?
First, calling ToUniversalTime() on DateTime.UtcNow is redundant, since .net 2.0, no conversion happens if the "Kind" of the source DateTime object is "Utc".
Other than that, this looks fine.
This seems correct, and you're following the golden rule of DateTime: Use UTC, display in local!
Your approach seems correct to me although I think it is more appropriate to use the DateTimeOffset structure, which is new since .NET 3.5.
I quote Anthony Moore:
Use DateTimeOffset whenever you are referring to an exact point in time. For example, use it to calculate "now", transaction times, file change times, logging event times, etc. If the time zone is not known, use it with UTC. These uses are much more common than the scenarios where DateTime is preferred, so this should be considered the default.
Use DateTime for any cases where the absolute point in time does not apply: e.g. store opening times that apply across time zones.
Use DateTime for interop scenarios where the information is a Date and Time without information about the time zone, e.g. OLE Automation, databases, existing .NET APIs that use DateTime, etc.
Use DateTime with a 00:00:00 time component to represent whole dates, e.g. Date of irth.
Use TimeSpan to represent times of day without a date.
So you could simply write:
this.mCreateDate = DateTimeOffset.Now;
//...
TimeSpan lifeTime = DateTimeOffset.Now - Foo.CreateDate;

Timestamp as UTC Integer

I Have a legacy database with a field containing an integer representing a datetime in UTC
From the documentation:
"Timestamps within a CDR appear in Universal Coordinated Time (UTC). This value remains
independent of daylight saving time changes"
An example of a value is 1236772829.
My question is what is the best way to convert it to a .NET DateTime (in CLR code, not in the DB), both as the UTC value and as a local time value.
Have tried to google it but without any luck.
You'll need to know what the integer really means. This will typically consist of:
An epoch/offset (i.e. what 0 means) - for example "midnight Jan 1st 1970"
A scale, e.g. seconds, milliseconds, ticks.
If you can get two values and what they mean in terms of UTC, the rest should be easy. The simplest way would probably be to have a DateTime (or DateTimeOffset) as the epoch, then construct a TimeSpan from the integer, e.g. TimeSpan.FromMilliseconds etc. Add the two together and you're done. EDIT: Using AddSeconds or AddMilliseconds as per aakashm's answer is a simpler way of doing this bit :)
Alternatively, do the arithmetic yourself and call the DateTime constructor which takes a number of ticks. (Arguably the version taking a DateTimeKind as well would be better, so you can explicitly state that it's UTC.)
Googling that exact phrase gives me this Cicso page, which goes on to say "The field specifies a time_t value that is obtained from the operating system. "
time_t is a C library concept which strictly speaking doesn't have to be any particular implementation, but typically for UNIX-y systems will be the number of seconds since the start of the Unix epoch, 1970 January 1 00:00.
Assuming this to be right, this code will give you a DateTime from an int:
DateTime epochStart = new DateTime(1970, 1, 1);
int cdrTimestamp = 1236772829;
DateTime result = epochStart.AddSeconds(cdrTimestamp);
// Now result is 2009 March 11 12:00:29
You should sanity check the results you get to confirm that this is the correct interpretation of these time_ts.

Categories

Resources