Return a formatted string representing the time differential between the specified start and end times. - CSharp System

CSharp examples for System:DateTime Format

Description

Return a formatted string representing the time differential between the specified start and end times.

Demo Code


using System.Collections;
using System;/*from  ww  w.  j a v  a 2  s.  c o m*/

public class Main{
        public static string GetPrettyDelta(TimeSpan ts) {
            string rez = "";
            if (ts.Days > 0) {
                rez = Convert.ToString(ts.Days) + " days, ";
            }
            if (ts.Hours > 0) {
                rez += Convert.ToString(ts.Hours) + " hours, ";
            }
            if (ts.Minutes > 0) {
                rez += Convert.ToString(ts.Minutes) + " minutes, ";
            }
            rez += Convert.ToString(ts.Seconds) + " seconds";
            return rez;
        }
        #endregion

        #region -------- GET PRETTY TIME DELTA --------
        /// <summary>
        /// Return a formatted string representing the time differential
        /// between the specified start and end times.				
        /// </summary>
        /// <param name="begin">The DateTime object representing the start</param>
        /// <param name="end">The DateTime object represending the end</param>
        /// <returns>The number of days, hours, minutes, and seconds returned as a formatted string</returns>
        public static string GetPrettyDelta(DateTime begin, DateTime end) {
            TimeSpan start = new TimeSpan(begin.Ticks);
            TimeSpan stop = new TimeSpan(end.Ticks);
            TimeSpan diff = stop.Subtract(start);
            return GetPrettyDelta(diff);
            //string rez = "";
            //if(diff.Days > 0){
            //    rez = Convert.ToString(diff.Days)+" days, ";
            //}
            //if(diff.Hours > 0){
            //    rez += Convert.ToString(diff.Hours)+" hours, ";
            //}
            //if(diff.Minutes > 0){
            //    rez += Convert.ToString(diff.Minutes)+" minutes, ";
            //}
            //rez += Convert.ToString(diff.Seconds)+" seconds";
            //return rez;
        }
}

Related Tutorials