Skip to content

Instantly share code, notes, and snippets.

@IQAndreas
Created November 16, 2013 21:12
Show Gist options
  • Save IQAndreas/7505384 to your computer and use it in GitHub Desktop.
Save IQAndreas/7505384 to your computer and use it in GitHub Desktop.
Gets the hour value and the "time period" (AM/PM) based on the 24-hour you pass in (this code is VERY verbose for clarity)
var h = new Date().getHours();
if (h == 0)
{
period = am
hours = 12
}
else if (h > 0 && h < 12)
{
period = am
hours = h
}
else if (h == 12)
{
period = pm
hours = 12
}
else if (h > 12 && h < 24)
{
period = pm
hours = h % 12
}
else if (h == 24)
{
period = am
hours = 12
// date.getHours() should NEVER return 24 or greater.
// If it has, something has gone horribly wrong!
}
// If you don't need to be verbose, this will suffice:
hours = (h % 12) || 12;
period = (h < 12) ? "AM" : "PM";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment