Any function which calculates the number of months including the current month? - c#

Datediff calculates the no of months between two dates, Is there any function which lets you to calculate the same thing but also includes the current month.
Datediff +1 would give the answer, but just wanted to know if theres any inbuilt method.

Nothing built-in, because it is just that simple to include the current month by adding one, given that you know the diff won't include the current month. It's elegant enough for most developers' needs.

Related

Excel functions to C# code

So I'm trying to convert this Excel cell calculation into C#, but I can't really make sense of what it's doing. I read over the EDATE definition and it still doesn't make too much sense.
IF(EDATE(B25,-12)>A25,((EDATE(B25,-12)-A25)/(EDATE(B25,-12)-EDATE(EDATE(B25,-12),-12)))+1,(B25-A25)/(B25-EDATE(B25,-12)))
B25 = End Date
A25 = Start Date
It's essentially trying to calculation a fraction of a year. Should be very easy to do, but I'm not entirely sure what this EDATE thing does.
According to EDATE, you're mostly dealing with 12 months before the End Date (B25).
Given that, this seems to say:
If the start date is more than 12 months before the end date then:
(The amount of time that the start date is prior to the year before the end date divided by one year) + 1
Else:
The amount of time that the start date is prior to the end date divided by one year.
I really don't know how Excel handles date arithmetic or what the point of this function is, but that's my pseudo at a glance.
Really, it's just checking the if condition I mentioned, then offsetting the entire arithmetic by a year if the condition is true.
Edit
Okay, some quick research shows that Excel does date arithmetic purely as days, so then 12/1/1900 - 1/1/1900 = 335 days. Putting a time on either date makes it a fraction of a day.
Given that, this Excel formula appears to attempt to calculate the fractional year difference between the two dates.
This is a rough piece of code that should provide it:
TimeSpan span = endDate.Subtract(startDate);
double years = span.Days / 365.25;

C# - calculate if a date is six months older

I am trying to calculate if the given specified date is at least six months old. I am doing this:
if(DateTime.Now.AddMonths(-6)>date)
{
//Do something
}
Is this correct?
Some people say that this approach is wrong and will not give accurate results. Is the above is correct?
"6 months" is not a precise amount of time. It depends on the length of the months. In particular, you may well get different results from your calculation compared with date.AddMonths(6) < DateTime.Now. (Consider adding 6 months from August 30th vs taking away 6 months from February 28th... You may be okay, but you need to think about this carefully.)
You need to consider a few things carefully:
You're currently using DateTime.Now instead of DateTime.Today; how do you want the current time of day to affect things?
Is the "kind" of date UTC, unspecified or local? It makes a difference - DateTime is confusing, unfortunately.
How do you want to handle situations like the ones in the first paragraph?
Ultimately, if people are telling you it will not give accurate results, you should ask them for specific examples - you need to get a wealth of input data and desired results, add automated tests for them, and get them to pass. Then if anyone claims your code isn't working correctly, you should be able to challenge them to create another test case which fails, and justify their decision.
If you are only concerned about the date and not the time, use DateTime.Now.Date instead. Apart from that, I do not see any problems with the code you already have.

Strategy for Incomplete Dates

Working on an application where we would like the user to be able to enter incomplete dates.
In some cases there will only be a year - say 1854, or there might be a year and a month, for example March 1983, or there may be a complete date - 11 June 2001.
We'd like a single 'date' attribute/column - and to be able to sort on date.
Any suggestions?
Store the date as an integer -- yyyymmdd.
You can then zero out any month or day component that has not been entered
Year only: 1954 => 19540000
Year & Month: April 2004 => 20040400
January 1st, 2011 => 20110101
Of course I am assuming that you do not need to store any time of day information.
You could then create a struct to encapsulate this logic with useful properties indicating which level of granularity has been set, the relevant System.DateTime, etc
Edit: sorting should then work nicely as well
I can't think of a good way of using a single date field.
A problem you would get if you used January as the default month and 1 as the default day like others have suggested is, what happens when they actually pick January? How would you track if it's a selected January or a defaulted January.
I think you're going to have to store a mask along with the date.
You would only need a bit per part of the date, which would only be 6 bits of data.
M|D|Y|H|Min|S
Month Only 1|0|0|0|0|0 = 32
Year Only 0|0|1|0|0|0 = 8
Month+Year 1|0|1|0|0|0 = 40
AllButMinSec 1|1|1|1|0|0 = 60
You could put this into a Flag Enum to make it easier to use in code.
Well, you could do it via a single column and field that says 'IsDateComplete'.
If you only have the date field, then you'll need to encode the "incompleteness" in the date format itself, such that if the date is, say, < 1900, it's considered "Incomplete".
Personally, I'd go with an field on the side, that marks it as such. Easier to follow, easier to make decisions on, and allows for any dates.
It goes without saying, perhaps, that you can just create a date from DateTime.MinValue and then set what you "know".
Of course, my approach doesn't allow you to "know" what you don't know. (That is, you don't know that they've set the month). You could perhaps use a date-format specifier to mask that, and store it alongside as well, but it's potentially getting cumbersome.
Anyway, some thoughts for you.
One option is to use January as the default month, 1 as the default day, and 1900 or something like that as the default year. Incomplete dates would get padded out with those defaults, and incomplete dates would sort before complete ones in the same year.
Another, slightly more complex option is to use -1 for default day and year, and -1, 'NoMonth', or some such as the default month. Pad incomplete dates as above. This may make sorting a little hard depending on how you do it, but it gives you a way of telling which parts of the date are valid.
I know you'd rather have 1 column but, Instead of a single column one can always have a separate column for day, month and year. Not very difficult to do queries against, and it allways any of the components to be null.
Smehow encoding these states in the datetime itself will be harder to query.
What I did when last solving this problem, was to create a custom date type that kept track of which date parts was actually set and provided conversions to and from a DateTime. For storing in database i used one date field and then one boolean/bit to keep track of which date components that were actually set by the user.

Generating Calendars

How can I code a calendar? I mean how can I determine the days of the month, is the 1st a monday, tuesday or what. how many days are there in the particular month etc.
I use mainly PHP & C#. But I am mainly looking for the logic behind
Take a look at the DateTime type in the MSDN for C#.
You can determine the Weekday of a given day the following way:
var date = DateTime.Parse("16.10.2010");
Console.WriteLine(date.DayOfWeek);
If you are looking for the amount of days in a month, try this:
Console.WriteLine(DateTime.DaysInMonth(date.Year, date.Month));
Most languages (PHP and C# included) will provide utility functions or libraries which allow you to play with dates without having to get too involved in the gritty calculations.
PHP's date() and getdate() functions will tell you most details about a given date, including the day of week, day of month and day of year, provided you start with it in timestamp format.
If you want to find the details of the first of a given month, use the PHP mktime() function to get the time stamp for the date you want, then pass that into getdate() as above.
To find out how many days long a month is, you could either use a lookup table (ie Jan=31, etc), with a special case for Feb, or use the above method to get the 1st of the next month, and subtract 24 hours to get the last of the current month.
If you're using an up-to-date version of PHP (ie 5.3), there is a very useful new date class which supersedes most of the old date/time functionality, and provides a lot more besides. (it's also there in PHP 5.2, but not nearly as good as the 5.3 version).
Take a look at the GregorianCalendar class in C#. This will tell you what you need to know regarding a date according to different date "rules".
This will help you find things like the week number of a date that the DateTime class won't manage for you.

How does .NET determine the week in a TimeZoneInfo.TransitionTime?

Greetings
I'm trying to do some DateTime math for various time zones and I wanted to take daylight savings into account. Lets say I have a TimeZoneInfo and i've determined the appropriate AdjustmentRule for a given DateTime. Lets also say the particular TimeZoneInfo i'm dealing with is specified as rule.DaylightTransitionStart.IsFixedDateRule == false, so I need to figure out if the given DateTime falls within the start/end TransitionTime.Week values.
This is where I'm getting confused, what is .NET considering as a "week"? My first thought was it probably used something like
DayOfWeek thisMarksWeekBoundaries = Thread.CurrentThread.CurrentUICulture.DateTimeFormat.FirstDayOfWeek;
and went through the calendar assigning days to week, incrementing week every time it crossed a boundary. But, if I do this for May 2010 there are 6 week boundary buckets, and the max valid value for TransitionTime.Week is 5 so this can't be right.
Whats the right way to slice up May 2010?
This article http://msdn.microsoft.com/en-us/library/system.timezoneinfo.transitiontime.isfixeddaterule.aspx shows how to extract the IsFixedDateRule == false, see DisplayTransitionInfo
I finally realized whats going on, I think the property name "Week" is what threw me off. There might be 6 weeks in May (depending on how you count them), but any particular DayOfWeek shows up at most 5 times. The Week property doesn't really refer to what week the DayOfWeek is showing up in, its the nth DayOfWeek for that month--with the magic value 5 meaning its last so either the max n is 4 or 5 for a given month.

Categories

Resources