Get only time from Datetime in C#?


Hello, I was checking this How to show date time with am/pm using C# in ASP.NET? but I would like to know simple C# code to get only time from datetime in C#.  So for example, If I have  ' 09/04/2022 03:52 PM', i need only '03:53 PM'.


Asked by:- jaya
1
: 94 At:- 7/20/2022 2:59:37 PM
C# Get time from Datetime







1 Answers
profileImage Answered by:- vikas_jk

To get only time, you can use datetime.ToString("h:mm tt"), so condering your example, you can have below code and output

DateTime dt = DateTime.Parse("09/04/2022 03:52 PM");

		dt.ToString("HH:mm"); // 15:52 PM // 24 hour clock // hour is always 2 digits
		dt.ToString("hh:mm tt"); // 03:52 PM // 12 hour clock // hour is always 2 digits
		dt.ToString("H:mm"); // 15:52 // 24 hour clock
		Console.WriteLine(dt.ToString("h:mm tt")); // 3:52 PM // 12 hour clock

Fiddle link: https://dotnetfiddle.net/57UWOs

You can also check: How to add time in datetime in C#?

Thanks.

1
At:- 7/20/2022 3:06:49 PM
Thanks for easy and useful answer with fiddle. 0
By : jaya - at :- 7/20/2022 3:12:06 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use