tags:

views:

340

answers:

4

when i get the DateTime.Hour property, i always get the 24 hour time (so 6PM would give me 18).

how do i get the "12 hour" time so 6PM just gives me 6.

i obviously can do the check myself but i assume there is a built in function for this.

+3  A: 

How about:

DateTime.Hour % 12

That will give 0-11 of course... do you want 1-12? If so:

((DateTime.Hour + 11) % 12) + 1

I don't think there's anything simpler built in...

Jon Skeet
A: 

There's no built-in function, mainly because you shouldn't need it:

  • If you're doing this for output to the user, look at using a format string.
  • If you're doing this for a calculation, you can subtract datetimes or add timespans directly.

Outside of this, the math calculation is simple enough and already available in other answers here.

Joel Coehoorn
i am doing hour comparisons compared to an integer i am getting from another data source (which obviously only comes in 12 hour time)
ooo
Shouldn't you convert that other source to a datetime? Blindly comparing 12hour times is dangerous.
Joel Coehoorn
A: 

DateTime.Now.ToString("hh"); --> Using this you will get "06" for 18h.

Sergio
A: 

I don't know of any built in method, but you can always add an extension method to accomplish this.

Of course, you could always replace the code with the way you want to accomplish it.

public static class Extension
{
    public static int GetTwelveCycleHour(this DateTime dateTime)
    {
        if (dateTime.Hour > 12)
        {
            return dateTime.Hour - 12;
        }

        return dateTime.Hour;
    }
}
Aaron Daniels
Hour % 12 is simpler
Joel Coehoorn
I realized that after I posted my answer, so I added the comment "Of course, you could always replace the code with the way you want to accomplish it." My main point was that this question to me sounds like a good candidate for an extension method.
Aaron Daniels
I didn't want to just rip off Jon Skeet's answer into my own, so I only added the comment and didn't change the code.
Aaron Daniels