TimeSpan.Parse time format hhmmss

后端 未结 6 1505
忘掉有多难
忘掉有多难 2020-12-15 20:52

in c# i have time in format hhmmss like 124510 for 12:45:10 and i need to know the the TotalSeconds. i used the TimeSpan.Parse(\"12:45:10\").ToTalSeconds but it does\'nt tak

6条回答
  •  一向
    一向 (楼主)
    2020-12-15 21:04

    You have to decide the receiving time format and convert it to any consistent format.

    Then, you can use following code:

    Format: hh:mm:ss (12 Hours Format)

    DateTime dt = DateTime.ParseExact("10:45:10", "hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
    double totalSeconds = dt.TimeOfDay.TotalSeconds;    // Output: 38170.0
    

    Format: HH:mm:ss (24 Hours Format)

    DateTime dt = DateTime.ParseExact("22:45:10", "HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
    double totalSeconds = dt.TimeOfDay.TotalSeconds;    // Output: 81910.0
    

    In case of format mismatch, FormatException will be thrown with message: "String was not recognized as a valid DateTime."

提交回复
热议问题