C#全小时格式

时间:2012-06-07 08:00:20

标签: c# datetime formatting

我有一个样本日期

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

我怎样才能达到49:01:03的经过时间?我不能得到任何字符串格式,包括几天。

目前我想在DataGridView的Columns上使用它。

以下是它的示例代码:

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

但是我无法让它发挥作用:(。

注意:我在减去日期和时间方面没有任何问题。我在询问格式。

  

已关闭:刚刚使用了从IFormatProvider继承的包装类。

4 个答案:

答案 0 :(得分:3)

使用TimeSpan类:

TimeSpan ts = endDate - startDate;

然后你在TimeSpan课程中获得了所需的所有信息。我假设格式化不是问题。

答案 1 :(得分:1)

我认为可能没有这样的格式,所以你必须得到这些行的价值

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

另请查看此Custom Format provider

答案 2 :(得分:0)

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

myString应包含已用时间。检查thisthis是否有其他时间跨度格式。

答案 3 :(得分:0)

这对你有用吗?

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);
        }
    }
}

我不太确定如何在控件中显示它。您可能需要编写一个包装器类来实现一个正确的ToString(),然后将其传入。