Saturday, June 21, 2008

AM/PM

To those of you who have been bored by the recent string of math-related articles, I apologize. I still have a lot of math-related functions to share with you, but I do have other things to share with you as well, such as validation functions, string functions, and datetime functions. This week we'll take a look at one of those datetime functions.


In ASP, time values are normally in the format HH:MM:SS followed by AM or PM. Quite often, we don't want to include the seconds portion, so we extract the hours and minutes using the Hour() and Minute() functions respectively. Unfortunately, there is no quick function for extracting the AM/PM. Let's do something about that right now.


  1. function ampm(someTime)
  2.     if hour(someTime) < 12 then
  3.         ampm = "AM"
  4.     else
  5.         ampm = "PM"
  6.     end if
  7. end function

Now we can do stuff like this:
Hour(someTime) & ":" & Minute(someTime) & " " & ampm(someTime)


Those of you who are PHP programmers are hopefully aware that the same result can be achieved in PHP using the built-in date() function and specifying the letter A or a in the format string for uppercase or lowercase respectively:
date("g:i A", $timestamp)


View this code on Snipplr

No comments: