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

前端 未结 8 993
陌清茗
陌清茗 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条回答
  •  Happy的楠姐
    2021-01-04 05:29

    Assuming you are staying in a 24 hour range, you can achieve what you want by subtracting the negative TimeSpan from Today's DateTime (or any date for that matter), then strip the date portion:

    DateTime dt = DateTime.Today;
    dt.Subtract(-TimeSpan.FromHours(14)).ToShortTimeString();
    

    Yields:

    2:00 PM

提交回复
热议问题