Answered by:
Using DateTime to calculate time between two dates

Question
-
Hi All,
I'm fairly new to programming so I hope this question isn't too basic for you all. I'm writing a program and part of it needs to calculate the time difference in Months, Days, Minutes, Seconds from Now and a date in the future (that the user has previously entered and is stored in a variable). I was wondering if anyone has any idea on how to go about this?
Basically the user is asked for a certain date in the future (their birthday), which is stored in variable userDate. The program then gets the dateTime.Now date and calculates this, then displays Months=a, weeks=b, days=c, hours=d (where a,b,c,d are the relevant numbers calculated).
i look forward to any ideas people have.
Many thanks
Paul
Answers
-
Try this:
DateTime t1 = DateTime.Now; DateTime t2 = new DateTime(2011, 8, 9); //yesterday TimeSpan ts = t1.Subtract(t2); Messagebox.Show(String.Format("Difference between two dates is: {0} days, {1} hours, {2} minutes, {3} seconds.", ts.Days, ts.Hours, ts.Minutes, ts.Seconds));
Mitja
All replies
-
DateTime d1 = DateTime.Now; DateTime d2 = new DateTime(2011, 1, 1); TimeSpan ts = d1 - d2;
You can use TotalMonths, TotalDays, TotalHours and such properties of TimeSpan. See help for TimeSpan for more info.
Tan Silliksaar milemarx.com- Proposed as answer by Esref Durna Thursday, August 11, 2011 8:16 AM
-
Try this:
DateTime t1 = DateTime.Now; DateTime t2 = new DateTime(2011, 8, 9); //yesterday TimeSpan ts = t1.Subtract(t2); Messagebox.Show(String.Format("Difference between two dates is: {0} days, {1} hours, {2} minutes, {3} seconds.", ts.Days, ts.Hours, ts.Minutes, ts.Seconds));
Mitja -
Assuming a and b are of type DateTime:
Messagebox.Show(String.Format("Difference between two dates is: {0} days, {1} hours, {2} minutes,
{3} seconds."
, (a - b).TotalDays.toString(), (a - b).TotalHours.ToString(), (a - b).TotalMinutes.ToString(),
(a - b).TotalSeconds.ToString()));
My Blogs -
-
Hi Paul,
I have tried @Mitja's code, which is working fine on my side, what about you?
Have a nice day,
Jackie Sun [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
-