Freddie Fabregas
Freddie Fabregas

Reputation: 1203

C# full hour format

I have a sample date

DateTime startDate = DateTime.Parse("2011-01-01 00:00:00");
DateTime endDate = DateTime.Parse("2011-01-03 01:01:03");

How can I get it to Elapsed time of 49:01:03? I can't get any string format including days.

Currently I want to use that on DataGridView's Columns.

Below is the sample code of it:

private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
    e.Column.CellTemplate.Style.FormatProvider = new DayToHour();
    //e.Column.CellTemplate.Style.Format = "";
}

But I can't get it work :(.

Note: I don't have any problem on subtracting the date and time. I'm asking about the format.

Closed: Just used wrapper class inheriting from IFormatProvider.

Upvotes: 0

Views: 496

Answers (4)

V4Vendetta
V4Vendetta

Reputation: 38200

I think there might no such format available so you will have to get the value on these lines

TimeSpan diff = endDate - startDate;
String.Format("{0:00}hr {1:00}mn {2:00}sec",
                     Math.Truncate(diff.TotalHours),diff.Minutes,diff.Seconds);

Also have a look at this Custom Format provider

Upvotes: 1

Matthew Watson
Matthew Watson

Reputation: 109567

Does this work for you?

using System;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime startDate = DateTime.Parse("2011-01-01 00:00:00");
            DateTime endDate = DateTime.Parse("2011-01-03 01:01:03");

            TimeSpan elapsed = endDate - startDate;

            string result = string.Format("{0:d2}:{1:d2}:{2:d2}", elapsed.Days*24 + elapsed.Hours, elapsed.Minutes, elapsed.Seconds);

            Console.WriteLine(result);
        }
    }
}

I'm not too sure how you will get that displayed in the control. You might need to write a wrapper class that implements a ToString() that does the right thing, and pass that in.

Upvotes: 0

zmashiah
zmashiah

Reputation: 153

Use the TimeSpan class:

TimeSpan ts = endDate - startDate;

Then you got in TimeSpan class all the information you need. I am assuming formatting is not the issue.

Upvotes: 3

Jcl
Jcl

Reputation: 28272

TimeSpan tp = endDate.Subtract(startDate);
string myString = tp.ToString("c");

myString should contain the elapsed time. Check this and this for other timespan formats.

Upvotes: 0

Related Questions