I have two dates, one less than the other. I want to create a string such as this one
\"0 days, 0 hours, 23 minutes, 18 seconds\"
representing the differenc
When you subtract one DateTime from another, you get a TimeSpan instance, which exposes those values.
TimeSpan diff = DateTime.Now - DateTime.Today;
string formatted = string.Format(
CultureInfo.CurrentCulture,
"{0} days, {1} hours, {2} minutes, {3} seconds",
diff.Days,
diff.Hours,
diff.Minutes,
diff.Seconds);
Have you tried using
TimeSpan()
that can certainly do what you want
TimeSpan diffTime = dateTimeNew -PreviousDate;
int days=diffTime.Days;
int hours=diffTime.Hours;
int minutes=diffTime.Minutes;
int seconds=diffTime.Seconds;
Don't forget that if you want this calculation to be portable you need to store it as UTC and then when you display it convert to local time. As a general rule Store dates as UTC and convert to local time for presentation.
How about something like this?
TimeSpan diff = dateTimeNew - dateTimeOld;
string output = string.Format("{0} days, {1} hours, {2} minues, {3} seconds", diff.Days, diff.Hours, diff.Minutes, diff.Seconds);
Console.WriteLine(output);
DateTime myDay = DateTime.Now;
DateTime otherDate = DateTime.Now.AddYears(1);
var test = otherDate.Subtract(myDay);
Console.WriteLine("Days:" + test.Days + "Hours:" + test.Hours +"Minutes" + test.Minutes +"Seconds" + test.Seconds);
Here test is of type TimeStamp