Calculate date difference in months [closed] - c#

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a field returning a year and month value. For example, 20119 (2011 is year and 9 is for September). How could I compare that to the current year and month to get the difference in months? For example, in the same format the current year and month would be 20135, so the value I would be looking for would be 20. 20135 minus 20 months would be 20119. Not sure how to construct the formula to dynamically calculate the difference in months using date functions, perhaps.

Try this
DateTime x1 = DateTime.ParseExact("20119", "yyyyM", CultureInfo.InvariantCulture);
DateTime x2 = DateTime.ParseExact("20135", "yyyyM", CultureInfo.InvariantCulture);
int months = Math.Abs((x2.Month - x1.Month) + 12 * (x2.Year - x1.Year));

First I am assuming that by your question:
Single date months will have one digit
The value of the Year+Month is a string (if it is an int, throw a ToString() on the in value in the code below)
Your value thus will be 5-6 digits in length. You can perform the code below in less lines, but forgive my verbose answer - I will add extra code to make this more clear:
We can get the current date only as month year by getting using Date.Now
// Just want the month/year
DateTime currentDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
Now we can get your date for to test against the current year/month using a substring method (remember my assumption that we are dealing with a string value, and to convert ToString() if not).
// breaking out test date to year/month portions and saving as a new date time
string testDateValue = "20119";
int testDateYear = Convert.ToInt32(testDateValue.Substring(0, 4));
int testDateMonth = Convert.ToInt32(testDateValue.Substring(4));
DateTime testDate = new DateTime(testDateYear, testDateMonth, 1);
Now lets get the difference:
// get month dif - remove abs() if want negative if test date in future
int numberOfMonths = Math.Abs(((currentDate.Year - testDate.Year) * 12) +
(currentDate.Month - testDate.Month));
Now - if you want to compare 2 days in the yyyym format instead of using current date, just do the year/month conversion listed above and then perform the month dif formula on that.

Why not multiply the year by number of months in a year for each date field and then return the difference?

You can use the class DateDiff class from the Time Period Library for .NET, to calculate the months:
// ----------------------------------------------------------------------
public void CalcMonths( DateTime epoch )
{
DateDiff dateDiff = new DateDiff( DateTime.Now, epoch );
Console.WriteLine( "{0} months", dateDiff.Months );
// > 1 Year 4 Months 12 Days 12 Hours ago
} // CalcMonths

You can basically split the string.
int a = 201410;
int b= 20139;
int year1 = int.Parse(a.ToString().Substring(0,4));
int year2 = int.Parse(b.ToString().Substring(0,4));
int month1 = int.Parse(a.ToString().Substring(4));
int month2 = int.Parse(b.ToString().Substring(4));
//now construct a date for each
DateTime date1 = new DateTime(year1, month1, 1);
DateTime date2 = new DateTime(year2, month2, 1);
//then subtract them and make it months
int numberOfMonths = ((date1.Year - date2.Year) * 12) + date1.Month - date2.Month;

This is a code snippet from the solution posted on MSDN (link):
DateTime oldDate = new DateTime(2002,7,15);
DateTime newDate = DateTime.Now;
// Difference in days, hours, and minutes.
TimeSpan ts = newDate - oldDate;
// Difference in days.
int differenceInDays = ts.Days;
Should work for years/months as well (something like the following):
int differenceInMonths = (ts.Years *12 + ts.Months);
Hope this will help.
Rgds, AB

Related

c# datetime create Day of Week Hour and Min [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How do i go about creating a datetime based on only the following information:
Day of Week, Hour & Minuet.
I.e. I don't care what month it is or even what the date is (i don't have that info in the database).
I thought i could parse them as a string but is turning out to be more difficult than i thought.
Created on function for you it might be helpful to you ..
public DateTime CreateDayOfWeek(int DayOfWeek,int hour,int min)
{
DateTime dt = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,hour,min,0);
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysUntilTuesday = (DayOfWeek - (int)dt.DayOfWeek + 7) % 7;
// DateTime nextTuesday = today.AddDays(daysUntilTuesday);
dt = dt.AddDays(daysUntilTuesday);
return dt;
}
I have tested for several dates and its working for me ..
let me know if you have any issue ..
Here is .netFiddle
You can create your date like this...
var hour = 1; // you set this from code
var minute = 1; // set this from code
var now = DateTime.Now;
var tempDateTime = new DateTime(now.Year, now.Month, now.Day, hour, minute, 0);
// Make this enum whatever you want your date to be...
var num = (int)DayOfWeek.Sunday;
var dateForComparison = tempDateTime.AddDays(num - (int)tempDateTime.DayOfWeek);
Now dateForComparison holds a date that has your time values set and the day of week you have specified.
You said you don't care about what month or date it is, which makes me assume you want any date as long as it is the right day of week and time (hour and minute). You can do it like this:
var date = new System.DateTime(2016, 9, 25);
date = date.AddDays(dow).AddHours(hours).AddMinutes(minutes);
September 25, 2016 was a Sunday. Add the day of the week (Sunday = 0) and you get the correct day. Then add the hours and minutes. Of course, if you like you can pick any Sunday of any month/year to start.
You can create a function for build your date:
public DateTime BuildDate(Int32 day, Int32 hour, Int32 minute)
{
var now = DateTime.Now;
var initialDate = now.AddDays(((Int32)now.DayOfWeek + 1) * -1);
return new DateTime(initialDate.Year, initialDate.Month, initialDate.AddDays(day).Day, hour, minute, 0);
}
The day of week is start from sunday in this case.
You can use: DateTime.ToString Method (String)
DateTime.Now.ToString("ddd HH:mm") // for military time (24 hour clock)
More: https://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

How to compare a given date from today

I want to compare a given date to today and here is the condition: If provided date is greater than or equal to 6 months earlier from today, return true else return false
Code:
string strDate = tbDate.Text; //2015-03-29
if (DateTime.Now.AddMonths(-6) == DateTime.Parse(strDate)) //if given date is equal to exactly 6 months past from today (change == to > if date has to be less 6 months)
{
lblResult.Text = "true"; //this doesn't work with the entered date above.
}
else //otherwise give me the date which will be 6 months from a given date.
{
DateTime dt2 = Convert.ToDateTime(strDate);
lblResult.Text = "6 Months from given date is: " + dt2.AddMonths(6); //this works fine
}
If 6 months or greater than 6 months is what I would like for one
condition
If less than 6 months is another condition.
Your first problem is that you're using DateTime.Now instead of DateTime.Today - so subtracting 6 months will give you another DateTime with a particular time of day, which is very unlikely to be exactly the date/time you've parsed. For the rest of this post, I'm assuming that the value you parse is really a date, so you end up with a DateTime with a time-of-day of midnight. (Of course, in my very biased view, it would be better to use a library which supports "date" as a first class concept...)
The next problem is that you are assuming that subtracting 6 months from today and comparing it with a fixed date is equivalent to adding 6 months to the fixed date and comparing it with today. They're not the same operation - calendar arithmetic just doesn't work like that. You should work out which way you want it to work, and be consistent. For example:
DateTime start = DateTime.Parse(tbDate.Text);
DateTime end = start.AddMonths(6);
DateTime today = DateTime.Today;
if (end >= today)
{
// Today is 6 months or more from the start date
}
else
{
// ...
}
Or alternatively - and not equivalently:
DateTime target = DateTime.Parse(tbDate.Text);
DateTime today = DateTime.Today;
DateTime sixMonthsAgo = today.AddMonths(-6);
if (sixMonthsAgo >= target)
{
// Six months ago today was the target date or later
}
else
{
// ...
}
Note that you should only evaluate DateTime.Today (or DateTime.Now etc) once per set of calculations - otherwise you could find it changes between evaluations.
Try with this
DateTime s = Convert.ToDateTime(tbDate.Text);
s = s.Date;
if (DateTime.Today.AddMonths(-6) == s) //if given date is equal to exactly 6 months past from today (change == to > if date has to be less 6 months)
{
lblResult.Text = "true"; //this doesn't work with the entered date above.
}
replace == with >= or <= according to your needs

Operate between datetimepickers [duplicate]

This question already has answers here:
How to subtract a datetime from another datetime?
(7 answers)
Closed 9 years ago.
I am trying to get the difference between two datetimepickers.
For example:
Between X date and Y date, have been past X days, Y months and Z years.
So, if I'd put in the first datetimepicker my birth date and in the second the day of today, I would my exact age, for example: "20 days, 3 months and 26 years".
I tried a few codes, but the results are not correct.
Thanks in advance.
The code is:
string age = "Tu age es de:\n";
age = age + ((Math.Abs(DateTime.Today.Day - dtpage.Value.Day)).ToString()) + " days, ";
age = age + ((Math.Abs(DateTime.Today.Month - dtpage.Value.Month)).ToString()) + " months";
age = age + " y " + ((Math.Abs(DateTime.Today.Year - dtpage.Value.Year)).ToString()) + " years";
MessageBox.Show(age);
EDIT: Solved in C# calculate accurate age
Please show the code if this answer is not sufficient, but if you're talking about DateTime objects, just use the Subtract method.
Try This:
DateTime birthdayDate = DateTime.Now; //get the date from datetimepicker
var dateTimeResult = DateTime.Now.Subtract(birthdayDate);
I think Datediff will accomplish this.
Edit - here:
string diff = DateAndTime.DateDiff(DateInterval.Second, DateTimePicker1.Value, DateTimePicker2.Value);
Interaction.MsgBox(diff);
Now just format the seconds.
I think you might have to write a couple of your own lines of code, which is not too hard if you look at your classes. Here is a simple example, you may need to check for a negative month value and if so add 12 to it, since you would be carrying a year over.
DateTime d = DateTime.Now;
DateTime d2 = DateTime.Now.AddMinutes(-28938923);
int years = d.Year - d2.Year;
int months = d.Month - d2.Month;
int days = d.Day - d2.Day;
if (days < 0)
{
// borrow a month
months--;
// use your brain power to pick the correct month. I have not thought this step out.
days += DateTime.DaysInMonth(d.Month);
}
if (months < 0)
{
// borrow a year
years--;
months += 12;
}

C# DateTime subtraction hours from an DateTime Variable [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I want to compare to dates like :
I have an Variable DateTime, and I want compare if the TIME of this variable is smaller than actual TIME ...
ex:
Datetime DateT = new DateTime.Now;
string Myvariable = "13:00:36";
You can use DateTime.TryParseExact Method and DateTime.TimeOfDay Property as below
string value = "13:00:36";
DateTime dt;
if (DateTime.TryParseExact(value, "HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
if (dt.TimeOfDay > DateTime.Now.TimeOfDay)
{
// greater than actual time
}
else
{
// smaller than actual time
}
}
Since you have time in string format it is difficult to compare. What you can do is convert it to Datetime by giving correct format string. Now you have two DateTime objects and you can get Time of those object by TimeOfDay property and compare..
Have you tried to use the DateTime variable instead? Something like this:
DateTime date1 = new DateTime(2013, 1, 1, 13, 00, 36);
DateTime dateNow = new DateTime.Now;
Console.WriteLine(date1.ToString("T", CultureInfo.CreateSpecificCulture("es-ES")));
// Outputs 6:30:00
Console.WriteLine(date1.ToString("U", CultureInfo.CreateSpecificCulture("en-US")));
// Outputs Tuesday, January 1, 2013 13:00:36 PM
Console.WriteLine(dateNow.ToString());
// Outputs the current date/time
Then you can create another DateTime and compare them as DateTime variable, not strings, although you can still output the values as strings using date1.ToString() function.
More info about it here: http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
Hope it helps.
Use the following code to get the time string as a DateTime instance:
DateTime DateT = new DateTime.Now;
string Myvariable = "13:00:36";
DateTime parsedTime = DateTime.ParseExact(
Myvariable,
"HH:mm:ss",
CultureInfo.InvariantCulture);
The parsedTime will have the time components (Hour, Minute, Second) as given in the string variable, but it will have a different date. The Year, Month and Day components are not present in the string, so they will default to the date of DateTime.MinValue.Date. In order to compare correctly, you need to compare only the time parts:
bool isParsedGreater = parsedTime.Hours > DateT.Hours
&& parsedTime.Minutes > DateT.Minutes
&& parsedTime.Seconds > DateT.Seconds;

CLARION Date Conversion C# + DATE ADD/SUBTRACT

*(This is for ISV database so I am kind of reverse engineering this and cannot change) ...
How can I do the following date to int (visa/versa) conversion in C# ...
So Say the Date is:
5/17/2012
it gets converted to int
77207
in the database.
At first I thought this was a Julian date however it does not appear to be the case. I was fooling around with the method from Julian Date Question however this does not match up.
var date = ConvertToJulian(Convert.ToDateTime("5/17/2012"));
Console.WriteLine(date);
public static long ConvertToJulian(DateTime Date)
{
int Month = Date.Month;
int Day = Date.Day;
int Year = Date.Year;
if (Month < 3)
{
Month = Month + 12;
Year = Year - 1;
}
long JulianDay = Day + (153 * Month - 457)
/ 5 + 365 * Year + (Year / 4) -
(Year / 100) + (Year / 400) + 1721119;
return JulianDay;
}
Outputs 2456055 //Should be 77207
I've been using this SQL to do the conversion:
SELECT Convert(date, CONVERT(CHAR,DATEADD(D, 77207, '1800-12-28'),101))
and it appears to be accurate. How could I do this conversion in C# ? And can someone edify me as to what standard this is based on or is it simply a random conversion. Thanks in advance.
//TO int
var date = new DateTime(1800,12,28,0,0,0);
var daysSince = (DateTime.Now-date).Days;
//FROM int
var date = new DateTime(1800, 12, 28, 0, 0, 0);
var theDate = date.AddDays(77207);
This appears to be a Clarion Date:
the number of days that have elapsed since December 28, 1800
Allegedly to, Display Clarion Dates In Excel it only takes
subtracting 36161 from the value and formatting it as a date
If it is a linear formula, you should be able to calculate formula in the form of y=mx+b. You would need a minimum of two data points.
Here is the vb.net Code I use to convert Clarion Date to Julian Date:
Dim ldblDaysToSubtract As Double = 36161.0
mclsRevEmployeeRecd.BirthDate(istrBirthDate:=(CDbl(E1Row.Item("BIRTH_DT")) - ldblDaysToSubtract).ToString)
mstrBirthDate = Format(CDate(Date.FromOADate(CDbl(istrBirthDate)).ToString), "MM/dd/yyyy")

Categories