[c#] How do I get the AM/PM value from a DateTime?

The code in question is below:

public static string ChangePersianDate(DateTime dateTime)
{
    System.Globalization.GregorianCalendar PC = new System.Globalization.GregorianCalendar();
    PC.CalendarType = System.Globalization.GregorianCalendarTypes.USEnglish;
    return
    PC.GetYear(dateTime).ToString()
    + "/"
    + PC.GetMonth(dateTime).ToString()
    + "/"
    + PC.GetDayOfMonth(dateTime).ToString()
    + ""
    + PC.GetHour(dateTime).ToString()
    + ":"
    + PC.GetMinute(dateTime).ToString()
    + ":"
    + PC.GetSecond(dateTime).ToString()
    + " "
    ????????????????
}

how can I get the AM/PM from the dateTime value?

This question is related to c# .net datetime datetime-format gregorian-calendar

The answer is


its pretty simple

  Date someDate = new DateTime();
  string timeOfDay = someDate.ToString("hh:mm tt"); 
  // hh - shows hour and mm - shows minute - tt - shows AM or PM

You can test it in this way

Console.WriteLine(DateTime.Now.ToString("tt "));

The output will be like this:

AM

or

PM

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.

You can also look at the related topic:

How do you get the current time of day?


The DateTime should always be internally in the "american" (Gregorian) calendar. So if you do

var str = dateTime.ToString(@"yyyy/MM/dd hh:mm:ss tt", new CultureInfo("en-US"));

you should get what you want in many less lines.


string AM_PM = string.Format("{0:hh:mm:ss tt}", DateTime.Now).Split(new char[]{' '})[1];

@Andy's answer is Okay. But if you want to show time without 24 hours format then you may follow like this way

string dateTime = DateTime.Now.ToString("hh:mm:ss tt", CultureInfo.InvariantCulture);

After that, you should get time like as "10:35:20 PM" or "10:35:20 AM"


If you want to add time to LongDateString Date, you can format it this way:

    DateTime date = DateTime.Now;
    string formattedDate = date.ToLongDateString(); 
    string formattedTime = date.ToShortTimeString();
    Label1.Text = "New Formatted Date: " + formattedDate + " " + formattedTime;

Output:

New Formatted Date: Monday, January 1, 1900 8:53 PM 

Something like bool isPM = GetHour() > 11. But if you want to format a date to a string, you shouldn't need to do this yourself. Use the date formatting functions for that.


+ PC.GetHour(datetime) > 11 ? "pm" : "am"

For your example but there are better ways to format datetime.


I know this might seem to be extremely late.. however it may help someone out there

I wanted to get the AM PM part of the date, so I used what Andy advised:

dateTime.ToString("tt");

I used that part to construct a Path to save my files.. I built my assumptions that I will get either AM or PM and nothing else !!

however when I used a PC that its culture is not English ..( in my case ARABIC) .. my application failed becase the format "tt" returned something new not AM nor PM (? or ?)..

So the fix to this was to ignore the culture by adding the second argument as follow:

dateTime.ToString("tt", CultureInfo.InvariantCulture);

.. of course u have to add : using System.Globalization; on top of ur file I hope that will help someone :)


From: http://www.csharp-examples.net/string-format-datetime/

string.Format("{0:t tt}", datetime);  // -> "P PM"  or "A AM"

Very simple by using the string format

on .ToString("") :

  • 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 add "tt" ->> The Am/Pm designator.

exemple converting from 23:12 to 11:12 Pm :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("hh:mm tt");   // this show  11:12 Pm
var res2 = d.ToString("HH:mm");  // this show  23:12

Console.WriteLine(res);
Console.WriteLine(res2);

Console.Read();

wait a second that is not all you need to care about something else is the system Culture because the same code executed on windows with other langage especialy with difrent culture langage will generate difrent result with the same code

exemple of windows set to Arabic langage culture will show like that :

// 23:12 ?

? means Evening (first leter of ????) .

in another system culture depend on what is set on the windows regional and language option, it will show // 23:12 du.

you can change between different format on windows control panel under windows regional and language -> current format (combobox) and change... apply it do a rebuild (execute) of your app and watch what iam talking about.

so who can I force showing Am and Pm Words in English event if the culture of the >current system isn't set to English ?

easy just by adding two lines : ->

the first step add using System.Globalization; on top of your code

and modifing the Previous code to be like this :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.InvariantCulture); // this show  11:12 Pm

InvariantCulture => using default English Format.

another question I want to have the pm to be in Arabic or specific language, even if I use windows set to English (or other language) regional format?

Soution for Arabic Exemple :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.CreateSpecificCulture("ar-AE")); 

this will show // 23:12 ?

event if my system is set to an English region format. you can change "ar-AE" if you want to another language format. there is a list of each language and its format.

exemples :

ar          ar-SA       Arabic
ar-BH       ar-BH       Arabic (Bahrain)
ar-DZ       ar-DZ       Arabic (Algeria)
ar-EG       ar-EG       Arabic (Egypt)

big list...

make me know if you have another question .


Here is an easier way you can write the time format (hh:mm:ss tt) and display them separately if you wish.

string time = DateTime.Now.Hour.ToString("00") + ":" + DateTime.Now.Minute.ToString("00") + ":" + DateTime.Now.Second.ToString("00") + DateTime.Now.ToString(" tt");

or just simply:

 DateTime.Now.ToString("hh:mm:ss tt")

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to datetime-format

How do I convert 2018-04-10T04:00:00.000Z string to DateTime? Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8) How can I create basic timestamps or dates? (Python 3.4) Format Instant to String Laravel $q->where() between dates How to Convert datetime value to yyyymmddhhmmss in SQL server? AngularJS - convert dates in controller Display DateTime value in dd/mm/yyyy format in Asp.NET MVC Display date in dd/mm/yyyy format in vb.net Convert DataFrame column type from string to datetime, dd/mm/yyyy format

Examples related to gregorian-calendar

Specify the date format in XMLGregorianCalendar Using GregorianCalendar with SimpleDateFormat How do I get the AM/PM value from a DateTime? Simple conversion between java.util.Date and XMLGregorianCalendar