I have datetime saved in the database as "2019-04-06 15:22:23.150" now, how can show this date time value to user with am/pm using C# or Razor syntax in MVC View?
Sample output : 09/04/2019 03:52 PM
Thanks
You can use string.Format and tt to get AM/PM in C# time, take a look the below example
string.Format("{0:hh:mm:ss tt}", DateTime.Now)
This should give you the string value of the time. tt should append the am/pm.
DateTime.Now gives you current date/time of the day in C#.
In C# DateTime value you use the following :
To learn more about formats https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings read it.
Above answer works, But I would like to explain few more points.
When you will create datetime variable as below, you can get am/pm values.
DateTime datevariable = new DateTime(1, 1, 1, 22, 10, 0);
var TimeInPM = datevariable.ToString("hh:mm tt"); // this show 10:10 PM
var twentyFourHoursTime=datevariable.ToString("HH:mm"); // this shows 22:10
Console.WriteLine(TimeInPM);
Console.WriteLine(twentyFourHoursTime);
OR
If you just want to get the AM/PM part of the date, you can use below code
datevariable.ToString("tt");
Console.WriteLine(datevariable.ToString("tt")); // prints "PM" using above example
OR
If you have date in a date string like "02/22/2021 04:11", then you can parse it and show am/pm with it
var date= DateTime.ParseExact(
"02/22/2021 04:11 AM",
"M/dd/yyyy hh:mm tt",
System.Globalization.CultureInfo.InvariantCulture
);
Console.WriteLine(date);
Try this one to get all date and time with AM/PM in C#
DateTime dateTime = new DateTime(2022, 1, 1, 22, 10, 0);
var str = dateTime.ToString("dd/MM/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(str);
// prints 01/01/2022 10:10:00 PM
Thanks
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly