CSharp examples for System:DateTime Second
Displays the difference in time between the two dates. Return example is "12 years 4 months 24 days 8 hours 33 minutes 5 seconds"
// The contents of this file are subject to the New BSD using System;//from www.jav a 2 s . c om public class Main{ /// <summary> /// Displays the difference in time between the two dates. Return example is "12 years 4 months 24 days 8 hours 33 minutes 5 seconds" /// </summary> /// <param name="startTime">The start time.</param> /// <param name="endTime">The end time.</param> /// <returns></returns> public static string ReadableDiff(this DateTime startTime, DateTime endTime) { string result; int seconds = endTime.Second - startTime.Second; int minutes = endTime.Minute - startTime.Minute; int hours = endTime.Hour - startTime.Hour; int days = endTime.Day - startTime.Day; int months = endTime.Month - startTime.Month; int years = endTime.Year - startTime.Year; if (seconds < 0) { minutes--; seconds += 60; } if (minutes < 0) { hours--; minutes += 60; } if (hours < 0) { days--; hours += 24; } if (days < 0) { months--; int previousMonth = (endTime.Month == 1) ? 12 : endTime.Month - 1; int year = (previousMonth == 12) ? endTime.Year - 1 : endTime.Year; days += DateTime.DaysInMonth(year, previousMonth); } if (months < 0) { years--; months += 12; } //put this in a readable format if (years > 0) { result = years.Pluralize(YEAR); if (months != 0) result += ", " + months.Pluralize(MONTH); result += " ago"; } else if (months > 0) { result = months.Pluralize(MONTH); if (days != 0) result += ", " + days.Pluralize(DAY); result += " ago"; } else if (days > 0) { result = days.Pluralize(DAY); if (hours != 0) result += ", " + hours.Pluralize(HOUR); result += " ago"; } else if (hours > 0) { result = hours.Pluralize(HOUR); if (minutes != 0) result += ", " + minutes.Pluralize(MINUTE); result += " ago"; } else if (minutes > 0) result = minutes.Pluralize(MINUTE) + " ago"; else result = seconds.Pluralize(SECOND) + " ago"; return result; } }