Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the 12 hour date from DateTime

Tags:

c#

datetime

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.

like image 483
leora Avatar asked Aug 20 '09 13:08

leora


4 Answers

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...

like image 180
Jon Skeet Avatar answered Nov 08 '22 17:11

Jon Skeet


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

like image 35
Sergio Avatar answered Nov 08 '22 18:11

Sergio


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;
    }
}
like image 42
Aaron Daniels Avatar answered Nov 08 '22 18:11

Aaron Daniels


What about simply:

public static int GetTwelveCycleHour(this DateTime dateTime)
{
    return Convert.ToInt32(dateTime.ToString("h"));
}
like image 42
Michel St-Louis Avatar answered Nov 08 '22 16:11

Michel St-Louis