12 Hour Time: Simple Solution

12 Hour Time: Simple Solution

EDIT 07-FEB-2012: I made a free marketplace app for you all to test 
https://creator.zoho.com/public/showAppInfo?canvasurl=kqpjzaljg

There are a number of posts here about TIME in ZOHO Creator. Many have requested ZOHO supporting a 12 hour format. With some help from Gave a while back, I have been using a rather long function to verify if a user typed in proper 12 hour format (i.e. 12:15 am or 05:00 pm but NOT 1:15 or 07:00 PM). I found a better way to do this that only uses a few lines of code.

This uses ZOHO Creator's support for regular expressions (see a library of such things here). The code is below:

  1. test = (input.TIME).replaceFirst("^(1[0-2]|0[1-9]):[0-5]\d [ap]m","");
  2. if (test  ==  "")
  3. {
  4.     alert("correct");
  5. }
  6. else
  7. {
  8.     alert("wrong format");
  9. }

I'm no expert at RegEx, but I think the expression is at least mostly correct. It allows users typing extra spaces after the am or pm, though. I fixed that by allowing the text box only 8 characters.

Once you have validated the format, a little more ZOHO code can combine that with a date to obtain a date-time value. You'll need to convert this into 24 hr format (the second if block).

  1. test = (input.TIME).replaceFirst("^(1[0-2]|0[1-9]):[0-5]\d [ap]m","");
  2. if (test  ==  "")
  3. {
  4.     DT_String = zoho.currentdate + " " + (input.TIME).replaceAll(" [ap]m","") + ":00";
  5.     Date_Time = DT_String.toTime();
  6.     if (input.TIME.contains("pm"))
  7.     {
  8.         Date_Time = Date_Time.addHour(12);
  9.     }
  10.     alert(Date_Time);
  11. }
  12. else
  13. {
  14.     alert("wrong format");
  15. }