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

前端 未结 8 1006
陌清茗
陌清茗 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:35

    You need to convert the TimeSpan to a DateTime object first, then use whatever DateTime format you need:

    var t = DateTime.Now.TimeOfDay;
    
    Console.WriteLine(new DateTime(t.Ticks).ToString("hh:mm:ss tt"));
    

    ToShortTimeString() would also work, but it's regional-settings dependent so it would not display correctly (or correctly, depending on how you see it) on non-US systems.

提交回复
热议问题