How convert TimeSpan to 24 hours and minutes String?

前端 未结 5 895
生来不讨喜
生来不讨喜 2020-12-29 04:09

I use this code for converting Timespan to String (for ex: 14:53) :

myTimeSpan.ToString(\"hh:mm\");

but this erro

相关标签:
5条回答
  • 2020-12-29 04:53

    Try this will work 100% !!

    myTimeSpan.ToString(@"dd\.hh\:mm");.
    
    0 讨论(0)
  • 2020-12-29 04:55
    var result = string.Format("{0:D2}:{1:D2}",  myTimeSpan.Hours, myTimeSpan.Minutes);
    
    0 讨论(0)
  • 2020-12-29 04:59
    myTimeSpan.ToString(@"hh\:mm")
    

    Custom TimeSpan Format Strings

    The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh\:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.

    0 讨论(0)
  • 2020-12-29 05:04

    You need to use @"hh\:mm\" for TimeSpan. Timespan formatting is not exactly same as DateTime

    myTimeSpan.ToString(@"hh\:mm");
    

    Check out Msdn for more info

    0 讨论(0)
  • 2020-12-29 05:09

    From TimeSpan.ToString Method (String)

    TimeSpan t = new TimeSpan(14, 53, 0);
    Console.WriteLine(t.ToString(@"hh\:mm"));
    

    As an alternative you can use String.Format like;

    Console.WriteLine(String.Format("{0}:{1}", t.Hours, t.Minutes));
    
    • Standard TimeSpan Format Strings
    • Custom TimeSpan Format Strings

    Remember, TimeSpan.ToString(String) overload only avaiable for .NET 4 or higher.

    0 讨论(0)
提交回复
热议问题