how to convert 24-hour format TimeSpan to 12-hour format TimeSpan?

前端 未结 8 932
陌清茗
陌清茗 2021-01-04 05:17

I have TimeSpan data represented as 24-hour format, such as 14:00:00, I wanna convert it to 12-hour format, 2:00 PM, I googled and found something related in stackoverflow a

相关标签:
8条回答
  • 2021-01-04 05:53
    String formatted = yourDateTimeValue.ToString("hh:mm:ss tt");
    
    0 讨论(0)
  • 2021-01-04 05:54

    TimeSpan represents a time interval (a difference between times), not a date or a time, so it makes little sense to define it in 24 or 12h format. I assume that you actually want a DateTime.

    For example 2 PM of today:

    TimeSpan ts = TimeSpan.FromHours(14);
    DateTime dt = DateTime.Today.Add(ts);
    

    Then you can format that date as you want:

    String formatted = String.Format("{0:d/M/yyyy hh:mm:ss}", dt); // "12.4.1012 02:00:00" - german (de-DE)
    

    http://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.100%29.aspx

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