How can I String.Format a TimeSpan object with a custom format in .NET?

后端 未结 19 1492
情深已故
情深已故 2020-11-22 12:25

What is the recommended way of formatting TimeSpan objects into a string with a custom format?

19条回答
  •  旧巷少年郎
    2020-11-22 12:48

    Personally, I like this approach:

    TimeSpan ts = ...;
    string.Format("{0:%d}d {0:%h}h {0:%m}m {0:%s}s", ts);
    

    You can make this as custom as you like with no problems:

    string.Format("{0:%d}days {0:%h}hours {0:%m}min {0:%s}sec", ts);
    string.Format("{0:%d}d {0:%h}h {0:%m}' {0:%s}''", ts);
    

提交回复
热议问题