Get Time Distance - CSharp System

CSharp examples for System:TimeSpan

Description

Get Time Distance

Demo Code


using System.Globalization;
using System;/*from  w  w  w . ja  v a2 s.com*/

public class Main{
        public static string GetTimeDistance(string dTime)
        {
            try
            {
                DateTime dateValue = DateTime.Parse(dTime);
                return GetTimeDistance(dateValue);
            }
            catch (FormatException)
            {
                throw new Exception("DateTime convertion Exception");
            }
        }
        public static string GetTimeDistance(DateTime dateTime, string BeforePrefixCaption, string HourCaption, string MinuteCaption, string DateTimeFormat)
        {
            DateTime endTime = DateTime.Now;

            TimeSpan span = endTime.Subtract(dateTime);

            if (span.TotalMinutes < 5)
            {
                return BeforePrefixCaption + " " + span.Minutes.ToString() + " " + MinuteCaption;
            }
            else if (span.TotalMinutes < 60)
            {
                return BeforePrefixCaption + " " + ((span.Minutes / 5) * 5).ToString() + " " + MinuteCaption;
            }
            else if (span.TotalHours < 5)
            {
                return BeforePrefixCaption + " " + span.Hours.ToString() + " " + HourCaption;
            }
            else if (span.TotalHours < 24)
            {
                return BeforePrefixCaption + " " + span.Hours.ToString() + "  " + HourCaption;
            }

            return dateTime.ToString(DateTimeFormat);
        }
        public static string GetTimeDistance(DateTime dateTime)
        {
            return DateTimeHelper.GetTimeDistance(dateTime, "before", "hours", "minute", DateTimeHelper.DateFormatCRO);
        }
}

Related Tutorials