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'.
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.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly