I have a start date column called StartDate in a database table. I need to determine how many weeks elapsed from the start date until today.
Here is my code:
DateTime startDate = new DateTime(StartedDate);
if (startDate.addDays(7) == DateTime.Today) {
// One week elapsed.
}
Let's say startDate is 9/29/2016. If I add 7 days, the total becomes 10/7/2016.
If, for example, today is 10/7/2016 - the same date as above, so there is 1 week from the start date. How can I determine the number of weeks for dates in the future?
Try
if(DateTime.Now.Subtract(StartDate).TotalDays%7==0)
This will give you the modulus of days and equal 0 every 7 days. It will, however, be time sensistve (if StartDate is 2:00PM, days will be 6 until 2:00PM on day 7). If you are only concerned about the day (not time after midnight) use:
if(DateTime.Now.Date.Subtract(StartDate.Date).TotalDays%7==0)
Related
This code lets you calulate the difference in months between two dates, Date2 > Date1
public int MonthDiff(DateTime Date1, DateTime Date2)
{
return Math.Abs((Date2.Month - Date1.Month) + 12 * (Date2.Year - Date1.Year));
}
In my example if I put Date1 = "01/01/2019" & Date2 = "31/12/2019", it will return 11, and this is wrong, it should be 12.
Also if I put Date1 = "25/01/2019" & Date = "31/12/2019", it should be 12.
So the question should I need to calculate by Days or what?
I used this code
return Math.Abs(((Date2- Date1).Days / 30) + 12 * (Date2.Year - Date1.Year));
With Date1 = "01/01/2019" & Date2 = "31/12/2020", it shows 36 Months.
If you want to know the difference between two dates in variable length units like months or years, you should use the built in timespan functionality rather than roll your own, and accept some compromises/approximations. The average number of days in a year is 365.2425. The average number of days in a month is 30.42 for a non leap year or 30.50 for a leap year, or 30.44 overall. Choose one of these values when approximating the months. Choose whether to round down, or round up, and to how many decimal places when working out the months/years
For example:
var a = DateTime.Now;
var b = DateTime.Now.AddDays(366);
var years = Math.Round((b-a).TotalDays/365.2425);
You could take some alternative approaches like:
have an array of integers that depict the number of days in each month (over a four year period so leap February are accounted for) and a logic of "I will get the number of days between the two dates, then I will consider the month of the start date and set an array indexer variable pointing to that month in the a"rray-of-month-lengths", and I will subtract the number of days in that month from my total, then I'll move on to the next index in the array (going back to the array start if necessary) and subtract that.. and I'll keep doing it until the remaining total days is lower than the number of days in whatever month I'm looking at.. and the number of times I looped shall be the result of the number of months between the day"
write a loop that adds one day to the start date until the end date is breached, and count how many times the current month number is different to the month number on the last iteration of the loop
etc
These are decisions to implement very specific sorts of approximations
I don't think there is a good fact based answer to your question until you accurately explain every rule you want your math you work to, so all the exceptions can be coded for. Saying "x - y is 11 months and this is wrong" is not a rule; you need to say why it is wrong
Using c#, I want to compare the current week-to-date to the same period last week-to-date. For example, if today is Wednesday, and if the first day of the week is Sunday, then I want to compare totals for Sunday – Tuesday of this week against Sunday – Tuesday of last week. I’m not counting Wednesday because I don’t have a full day of data until midnight the same day.
The same applies to comparing this mtd to the same number of days last month, and last year. For example, if the current date is June 19th, I want to compare the data from May 1-18th of last month as well as January 1 – June 18th of last year against January 1 – June 18th of this year.
The variables I’m trying to use look like this:
//Current dates
DateTime currentDte = DateTime.Now;
DateTime beginWeek = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
DateTime beginMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
DateTime beginYear = new DateTime(DateTime.Now.Year, 1, 1);
//Historical dates
DateTime lastWeekToDate = DateTime.Now.StartOfWeek(DayOfWeek.Sunday - (7 - (int)DateTime.Now.DayOfWeek));
DateTime lastMonthToDate =
DateTime lastYearToDate =
As you can see I figured out the current dates and can loop through them to get the wtd, mtd, and ytd data I need. And I managed to figure out how to get the last week-to-date I need.
But I don’t know how to get the lastMonthToDate and lastYearToDate dates I need. I’ve tried everything I can think of. I’ve read date documentation until my eyes hurt, and still I come up with goose eggs. Can anyone offer any suggestions?
If I understand your question correctly, you just need to use AddMonths and AddYears.
DateTime lastMonthToDate = beginMonth.AddMonths(-1);
DateTime lastYearToDate = beginYear.AddYears(-1);
EDIT
Based your comment - it looks like you want the to subtract months/years from the current date in which case it would be
DateTime lastMonthToDate = currentDte.AddMonths(-1);
DateTime lastYearToDate = currentDte.AddYears(-1);
If it's the time of day that's throwing you off, just use the date part DateTime.Now.Date.AddMonths(-1)
Based on the feedback I received from Zeph, I was able to get the beginning of last year using this code:
DateTime startDate = beginYear.AddYears(-1);
Now I'm able to tally all of the ytd data I need based on the interval dates. Thank you very much!
I am making a loop where part of it will be creating new records and another part - should increment date field by one month without affecting the days, for every new record loop.
For example, default date is 2016/07/19 - dates for new records should go as follow - Record 1 - 2016/08/19; Record 2 - 2016/09/19; Record 3 - 2016/10/19
Here's a snippet of my code
startDate = (DateTime)target["xrm_startDate "];
while(a>b)
{
startDate = startDate.AddMonth(1);
}
With this loop, date is being increased by one month, however days outputted are different, depending on how many days month has.
There is no standard DateTime.AddMonth method. The DateTime.AddMonths method returns a date a given number of months later, with the day-part corrected if that day is not valid:
If the resulting day is not a valid day in the resulting month, the
last valid day of the resulting month is used. For example, March 31st
+ 1 month = April 30th
Are you looking for?
startDate = new DateTime(startDate.Day, startDate.Addmonths(1).Month, startDate.Year)
Also please check for the year.
I am using DateTime.Today.
Now I'm not sure if the date is from the beginning of the day or the end of the day.
This is what DateTime.Today returns : {11-3-2014 0:00:00}
MSDN states the following: "An object that is set to today's date, with the time component set to 00:00:00."
This means that a DateTime object is created with today's date at the absolute start of the day hence 00:00:00.
You can check if it is the start of the day by using the AddHour() method of the DateTime class.
DateTime d = DateTime.Today;
//AddHours, AddMinutes or AddSeconds
d = d.AddHours(1);
if (d.Date != DateTime.Today.Date)
{
//Not the same day
}
If d.date should be different the date was initialised at a different time (eg. 23:00:01).
http://msdn.microsoft.com/en-us/library/system.datetime.today(v=vs.110).aspx
0:00:00 is the start of the day and 23:59:59 is the end of day.
You can also confirm through this 24-hour clock
In the 24-hour time notation, the day begins at midnight, 00:00, and the last minute of the day begins at 23:59. Where convenient, the
notation 24:00 may also be used to refer to midnight at the end of a
given date[5] – that is, 24:00 of one day is the same time as 00:00 of
the following day.
On a side note:-
If you want to know the time then use .Now because that includes the 10:32:32 or whatever time; however .Today is the date-part only (at 00:00:00 on that day ie the begining of the day). So you can say that .Today is essentially the same as .Now.Date
Thats the beginning of the day, the end of the day would be:
{11-3-2014 23:59:59}
And remember, the only stupid question is the one you don't ask :)
DateTime.Today returns the current DateTime value, without the Time part.
Which means, it is the the first possible DateTime value for the current day.
Think of it like this:
The last moment in a day can be 23:59 or theoretically any amount of nanseconds before the next day. the next day then starts at 00:00:00 counting upwards.
So 11-3-2014 0:00:00 marks the beginning of a day. Either the earliest possible moment, or no time at all, if you want to treat 0:00:00 as a default value.
I'm writing a search program that includes a date range- DateFrom and DateTo, both of which are DateTimes. Searching January - April for any search criteria will return the results of January + February + March + April.
I would like to add functionality whereby a user can choose to search each month within a - range, so searching January - April will return each individual month's results. However I'm having trouble finding an intelligent way to implement this for any unit of time larger than days.
So far I'm getting a TimeSpan using:
TimeSpan ts = query.DateTo - query.DateFrom;
In a perfect world I'd just be able to do something like foreach (month m in TimeSpan){dostuff}, however TimeSpan stores dates as integers and does not include any units larger than days. Additionally, I thought maybe I could just use n = DateFrom.month - DateTo.month to get the difference in months and run a function in a for loop starting with DateFrom and lasting n months, but this won't work between years.
The last case is definitely fixable but includes a number of tedious special cases. Is there a cleaner / more elegant way of accomplishing this sort of iteration that I'm missing?
Thanks.
So for the basic pattern we can use a fairly simple for loop:
public static IEnumerable<DateTime> Months(DateTime start, DateTime end)
{
for (DateTime date = start; date < end; date = date.AddMonths(1))
yield return date;
}
Now in this case we have a start date that is inclusive and an end date that is exclusive. If we want to make the end date inclusive, as you have described, we can add:
end = end.AddMonths(1);
to the start of the method.
Next you have a few other considerations. Are the datetime objects passed in going to always be the first of the month? If not, how do you want to support it? If the start date is Feb 10th do you want the first yielded date to be Feb 1st (the start of the start date's month), March 1st (the first "first day of the month" on or after the start date), or Feb 10th (meaning that each date in the timespan would be the 10th day of that month)?
Those same questions also apply to the end date; do you want the last "first day of the month" before the end date, the first day of the next month, etc.
Also, what should happen if the start date is after the end date? Should it yield the dates "backwards", should it just pretend the start date is the end date and the end date is the start date? Should it keep adding days until you've overflowed DateTime and come back around to that date?
Pretty much all of these issues aren't too hard to deal with, the hard part is just knowing what you want to do in each case.
You could do something like:
var months = ((query.DateTo.Year - query.DateFrom.Year) * 12) + query.DateTo.Month - query.DateFrom.Month
for(int i=0;i<months;i++){
//do stuff as below
var currentDate=query.DateFrom.AddMonths(i);
}