How to show date time with am/pm using C# in ASP.NET?


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


Asked by:- manish
0
: 5222 At:- 4/9/2019 10:46:42 AM
ASP.NET MVC C# datetime-format






2 Answers
profileImage Answered by:- vikas_jk

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 :

  • if you use "hh" -> The hour, using a 12-hour clock from 01 to 12.
  • if you use "HH" -> The hour, using a 24-hour clock from 00 to 23.
  • if you use "mm" -> The minute, from 00 through 59.
  • if you use "m" - > The minute, from 0 through 59.
  • if you add "tt" -> The Am/Pm designator.

To learn more about formats https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings read it.

1
At:- 6/2/2019 9:54:27 AM


profileImage Answered by:- bhanu

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);
0
At:- 3/23/2021 3:55:44 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

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly