Although both versions shown in the title (small capitals, unpunctuated—am, pm—and lowercase, punctuated—a.m., p.m.) are standard, the latter tends to be stylistically and commonly preferred. Whichever style you choose, use it consistently.
The abbreviations stand for ante meridiem (before noon) and post meridiem (after noon) and are used strictly with the twelve-hour system. Since the abbreviations clarify part of day, do not add redundant detail—prefer, for example, 11 a.m. or 11 in the morning to 11 a.m. in the morning, though the first is most concise and thus best.
Regarding noon and midnight, you are correct to think that 12 a.m. and 12 p.m. are confusing. Since noon is the meridies, it cannot logically come before or after itself, and midnight, coming both twelve hours before and after noon, should then be both 12 a.m. and 12 p.m. Midnight is also often viewed as the end of day—suggesting p.m.—since conventional habits lead many of us to consider waking as the start of day. (If you find that notion absurd, before its 30th edition, the U.S. Government Style Manual recommended 12 a.m. for noon and 12 p.m. for midnight.) Some try to avoid the conundrum by writing 11:59 p.m. and 12:01 a.m., but doing so is clunky and admits to uncertainty. The solution? In both formal and informal writing, always prefer noon and midnight to 12 p.m. and 12 a.m., and when referring to midnight indicate the date or day as a range. You may thus plan lunch for Wednesday noon and expect submissions by midnight, June 9–10.
In the twenty-four-hour system, if numbers are required, 00:00 is midnight and 12:00 is noon.