A formatted string displaying the time elapsed between two dates - CSharp System

CSharp examples for System:DateTime Format

Description

A formatted string displaying the time elapsed between two dates

Demo Code


using System.Collections;
using System;/*from   w w  w  .ja  va  2  s  .  c  om*/

public class Main{
        /// <summary>
        /// A formatted string displaying the time elapsed between two dates
        /// </summary>
        /// <param name="begin">The DateTime object representing the start</param>
        /// <param name="end">The DateTime object represending the end</param>
        /// <returns>A formatted string displaying the time elapsed between the two dates</returns>
        public static System.Text.StringBuilder GetPreciseDelta(DateTime begin, DateTime end) {
            TimeSpan span = Delta(begin, end);
            string hh = Convert.ToString(span.Hours);
            string mm = Convert.ToString(span.Minutes);
            string ss = Convert.ToString(span.Seconds);
            string ms = Convert.ToString(span.Milliseconds);
            if (hh.Length == 1)
                hh = "0" + hh;
            if (mm.Length == 1)
                mm = "0" + mm;
            if (ss.Length == 1)
                ss = "0" + ss;

            int len = 4 - ms.Length;
            string buffer = "";
            for (int i = 0; i < len; i++) {
                buffer += "0";
            }
            ms = buffer + ms;


            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(hh);
            sb.Append(":");
            sb.Append(mm);
            sb.Append(":");
            sb.Append(ss);
            sb.Append(" ");
            sb.Append(ms);
            sb.Append("ms");
            return sb;
        }
}

Related Tutorials