251

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?

Brian Webster
  • 30,033
  • 48
  • 152
  • 225
SilverLight
  • 19,668
  • 65
  • 192
  • 300

15 Answers15

426

How about:

dateTime.ToString("tt", CultureInfo.InvariantCulture);
Andy
  • 7,646
  • 8
  • 46
  • 69
  • 3
    You need to add new System.Globalization.CultureInfo("en-US") in order to get this right (if you are not already running the thread in a US context) – thomas Jun 24 '15 at 11:06
  • 2
    @thomas - Good point. Edited now to specify `CultureInfo.InvariantCulture` – Andy Jun 24 '15 at 11:42
  • 9
    `ToString("tt", System.Globalization.CultureInfo.InvariantCulture)` – IndieTech Solutions Feb 01 '16 at 15:01
  • This for get AM/PM from date. But if I want to change AM to PM in any date. Then what should I do ? – Ajay Sharma Apr 14 '16 at 06:11
  • 2
    @AjaySharma Just add 12 hours before the format evaluation. `DateTime.Now.AddHours(12).ToString("tt", CultureInfo.InvariantCulture)` – AXMIM Mar 22 '17 at 20:41
  • Keep in mind that if you want to change PM to AM, you'd have to subtract 12 hours instead of adding it, assuming you want to preserve the same date. – Triynko May 07 '18 at 18:55
137
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?

Community
  • 1
  • 1
XikiryoX
  • 1,898
  • 1
  • 12
  • 33
  • 12
    This should be be lower case `hh` as your current representation outputs in 24hr time with am and pm which is a bit pointless – undefined Jan 13 '14 at 22:34
  • 1
    @LukeMcGregor I've amended the answer as per your suggestion. – Doctor Jones Feb 10 '14 at 16:14
  • I upvoted this answer and downvoted the accepted, because it didn't explain anything. This answer made sense, the other didn't. – jamheadart Dec 21 '20 at 14:56
  • @jamheadart lol, the accepted answer *from nearly a decade before* perfectly answers OP's question. They literally just had to cut'n'paste the answer into the space above the question marks. – mcalex May 28 '21 at 05:14
  • Answered it but didn't explain it. Using `"tt"` and `CultureInfo.InvariantCulture` is not self-explanatory to a newcomer. Even a one-liner can have an explanation. – jamheadart May 28 '21 at 07:59
57

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 shows 11:12 PM
var res2 = d.ToString("HH:mm");   // this shows 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 .

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Bilal
  • 1,254
  • 13
  • 14
50

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.

xanatos
  • 109,618
  • 12
  • 197
  • 280
19

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 :)

searchingSO
  • 207
  • 2
  • 9
  • 3
    Thanks for adding this as it helped me today - I was getting A.M. on my dev environment and AM on remote server and there was not a huge amount of help from google with it until I read this post. Even Dotnetpearls states "There are no periods in the output of tt. If you require periods in your AM or PM, you would have to manipulate the string." Which of course was completely untrue in my case ... – KiwiSunGoddess Mar 22 '15 at 20:15
16

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
Jamisco
  • 1,658
  • 3
  • 13
  • 17
10
+ PC.GetHour(datetime) > 11 ? "pm" : "am"

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

Kevin Holditch
  • 5,165
  • 3
  • 19
  • 35
  • See the link that @ChrisF has given above. Basically you can use to ToString method on the datetime object and pass it a format. This way you dont call datetime.ToString mulitple times as you are doing in your code example. – Kevin Holditch Oct 24 '11 at 12:06
  • 2
    As ugly as this may seem, it is a far simpler and more consistent way than messing around with different cultures. For example many cultures show time in 24hrs and do not include AM/PM at all, and ToString("tt") produces an empty string. – nathanchere Aug 09 '16 at 07:20
9

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

string.Format("{0:t tt}", datetime);  // -> "P PM"  or "A AM"
Baptiste Pernet
  • 3,318
  • 22
  • 47
5

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.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • 1
    Honestly, I wouldn't even show the isPM() method. THe *only* way to legitimately format DateTime objects is using the formatters. – richb01 Jul 23 '12 at 15:54
  • @richb01 I disagree. The only safe way is not to use am/pm at all and use 24h format, always append the invariant culture or doing it manually. "am" and "pm" are not filled in e.g. in German language, it's just empty. If somebody writes String.Format("{0:hh:mm tt}", DateTime.Now) they simply get wrong times – Christoph May 08 '15 at 14:05
3

@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"

Mahi
  • 1,019
  • 9
  • 19
2

You can test it in this way

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

The output will be like this:

AM

or

PM
yazarloo
  • 187
  • 1
  • 4
1

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 
Dennis R
  • 51
  • 5
1

Another option is to change the default culture used to get the right formatting. The advantage is that the new format will be used throughout the code.

CultureInfo.CurrentCulture = new CultureInfo("Fr-fr");
Console.WriteLine(DateTime.Now.ToString("t")); // 14:08

var customCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
customCulture.DateTimeFormat.AMDesignator = "am";
customCulture.DateTimeFormat.PMDesignator = "pm";
customCulture.DateTimeFormat.ShortTimePattern = "HH:mm tt";
CultureInfo.CurrentCulture = customCulture;

Console.WriteLine(DateTime.Now.ToString("t")); // 14:08 pm
Hoddmimes
  • 161
  • 1
  • 5
0

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")
Zero
  • 357
  • 2
  • 5
  • 20
-2
string AM_PM = string.Format("{0:hh:mm:ss tt}", DateTime.Now).Split(new char[]{' '})[1];
Praveen Manupati
  • 434
  • 1
  • 6
  • 12
Shah Bdr
  • 15
  • 3