Calculate difference between two dates in Hours and Minutes in C# and VB.Net

Last Reply 28 days ago By dharmendr

Posted 29 days ago

hello,

i am using this code to calculate the difference between 2 dates.

it works fine the only problem is i do not want days in it

for e.g start date: 1/aug/2019 and end date is till current date

so it shows 4 days, 200 hours and seco, i want to show only hours and min not days and second

so it should calculate all hours and min between start and end date

public string result { get; set; }
public void timecal(string startdate, string enddate)
{
    TimeSpan ts = DateTime.Parse(startdate) - DateTime.Parse(enddate);
    string lbl = "";
    if (ts.Days > 0 && ts.Hours > 0 && ts.Minutes > 0)
    {

        lbl = string.Format("{0:%d} days: {0:%h} hours: {0:%m} minutes", ts);
    }
    else if (ts.Days > 0 && ts.Hours > 0)
    {

        lbl = string.Format("{0:%d} days: {0:%h} hours", ts);
    }
    else if (ts.Hours > 0 && ts.Minutes > 0)
    {

        lbl = string.Format("{0:%h} hours: {0:%m} minutes", ts);
    }
    else
    {
        lbl = string.Format("{0:%d} days: {0:%h} hours: {0:%m} minutes", ts);
    }
    result = lbl;
}

 

Posted 28 days ago

Hi nauna,

Check this example. Now please take its reference and correct your code.

C#

protected void Page_Load(object sender, EventArgs e)
{
    timecal("1/aug/2019", DateTime.Now.ToString());
    Response.Write(result);
}

public string result { get; set; }
public void timecal(string startdate, string enddate)
{
    TimeSpan ts = DateTime.Parse(enddate) - DateTime.Parse(startdate);
    string lbl = "";
    if (ts.Days > 0)
    {
        lbl = string.Format("{0} hours: {1} minutes", ts.Days * 24 + ts.Hours, ts.Minutes);
    }
    else
    {
        lbl = string.Format("{0} hours: {1} minutes", ts.Hours, ts.Minutes);
    }

    result = lbl;
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    timecal("1/aug/2019", DateTime.Now.ToString())
    Response.Write(result)
End Sub

Public Property result As String
Public Sub timecal(ByVal startdate As String, ByVal enddate As String)
    Dim ts As TimeSpan = DateTime.Parse(enddate) - DateTime.Parse(startdate)
    Dim lbl As String = ""
    If ts.Days > 0 Then
        lbl = String.Format("{0} hours: {1} minutes", ts.Days * 24 + ts.Hours, ts.Minutes)
    Else
        lbl = String.Format("{0} hours: {1} minutes", ts.Hours, ts.Minutes)
    End If

    result = lbl

Output

518 hours: 4 minutes