Calculate Year Month Day Hour Minute Second between two dates using C# and VB.Net

Last Reply one month ago By dharmendr

Posted one month ago

i an facing an error in converting seconds to year,month,day.hours,minutes,seconds..i want the output as 2 year 2 months 5 days 1 hour 1 minute 1 second...likewise...reply plzz ..thanks in advance

protected void Button1_Click(object sender, EventArgs e)
    {
        DateTime dob = Convert.ToDateTime("20-01-2015 06:06:06");
        DateTime currentdate = Convert.ToDateTime("25-03-2017 07:07:07");
        TimeSpan time = currentdate.Subtract(dob);
         
        int xxx = Convert.ToInt32(time.TotalSeconds);
        int year=xxx/(24*3600*365);
        xxx = xxx % (24 * 3600 * 365);
        int month = xxx / (24 * 3600) / 30;
        xxx = xxx % (24 * 3600) / 30;
        int days = xxx / (24 * 3600);
        xxx= xxx % (24 * 3600);
     int hours = xxx / (3600);
      xxx=xxx % (3600);
        int minutes = xxx / 60;
        int seconds = xxx % 60;
        
       Response.Write(" year "+year.ToString()+" month "+month.ToString()+" days "+days.ToString());
      
    }

 

You are viewing reply posted by: dharmendr one month ago.
Posted one month ago

Hi jovceka,

Refer below code.

C#

protected void Page_Load(object sender, EventArgs e)
{
    DateTime currentdate = Convert.ToDateTime("03-25-2017 07:07:07");
    DateTime dob = Convert.ToDateTime("01-20-2015 06:06:06");
    TimeSpan ts = currentdate - dob;
    DateTime age = DateTime.MinValue + ts;
    int years = age.Year - 1;
    int months = age.Month - 1;
    int days = age.Day - 2;
    int hours = ts.Hours;
    int minutes = ts.Minutes;
    int seconds = ts.Seconds;
    Response.Write(String.Format("{0} year/s {1} month/s {2} day/s {3} hour/s {4} minute/s {5} second/s", years, months, days, hours, minutes, seconds));
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim currentdate As DateTime = Convert.ToDateTime("03-25-2017 07:07:07")
    Dim dob As DateTime = Convert.ToDateTime("01-20-2015 06:06:06")
    Dim ts As TimeSpan = currentdate - dob
    Dim age As DateTime = DateTime.MinValue + ts
    Dim years As Integer = age.Year - 1
    Dim months As Integer = age.Month - 1
    Dim days As Integer = age.Day - 2
    Dim hours As Integer = ts.Hours
    Dim minutes As Integer = ts.Minutes
    Dim seconds As Integer = ts.Seconds
    Response.Write(String.Format("{0} year/s {1} month/s {2} day/s {3} hour/s {4} minute/s {5} second/s", years, months, days, hours, minutes, seconds))
End Sub

Output

2 year/s 2 month/s 5 day/s 1 hour/s 1 minute/s 1 second/s