【问题标题】:Custom String Formatting, number to time自定义字符串格式,数字到时间
【发布时间】:2014-04-10 11:48:59
【问题描述】:

我想将数字转换为时间,比如

10  ->  00:10  
55  ->  00:55  
75  ->  01:15  
90  ->  01:30  
705 ->  11:45 

等等。我知道我可以编写一个方法并进行这种转换,但我需要它来处理DataGridView,所以我最好使用字符串Format

据我所知,没有实施这样的事情。我如何实现这种格式,以便可以在 Grid 的 DefaultCellStyle.Format 上设置它?

【问题讨论】:

    标签: c# .net datagridview string-formatting number-formatting


    【解决方案1】:

    您可以先从分钟创建TimeSpan

    TimeSpan minutes = TimeSpan.FromMinutes(705);
    

    然后使用DateTime.Add:

    DateTime dt = DateTime.Today.Add( minutes );
    

    现在你可以使用DateTime.ToString:

    string text = dt.ToString("HH:mm");
    

    您也可以使用TimeSpan.ToString(虽然DateTime.ToString 更具可读性):

    text = minutes.ToString(@"hh\:mm")
    

    您可以使用 DataGridViews CellFormatting 事件。

    How to: Customize Data Formatting in the Windows Forms DataGridView Control

    【讨论】:

    • 嗨蒂姆,感谢您的详细回答。所以我不能把它作为一种简单的格式,对吧?我之所以这么问,是因为 DataGridView 将 Format 作为字符串获取,而这个很棒的代码不能翻译成字符串,对吗?
    • 是的,据我所知。
    猜你喜欢
    • 1970-01-01
    • 2012-01-21
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多