Friday, July 07, 2006

Translate Time values with Javascript

11 On my current project, I have a need to convert a string to a valid time format. The user wants to be able to enter time in several formats. For example military time(1400), hour followed by a or p(2p), etc... I had a solution that got the job done, but it was getting long, was covered with bandaids and smelled like spaghetti. So I refactored it and came up with this approach. If you take out the comments, it has less than half the lines of code in the previous version. I use a trim string function to trim the spaces off the front and back of the time string, so I'm including it at the bottom.

Let me know if there is a better way to do this or if this might solve a problem you are having.


function fixTime(strTime)
{
var dayHalf = "a";
var Hour = "";
var Minute = "00";

// Drop the case
strTime = strTime.toLowerCase();

// Trim the spaces from the front and back
// of the string
strTime = TrimStr(strTime);

// Check for a|am|p|pm.
var amMatch = /(am|a|pm|p)$/.exec(strTime);
if(amMatch != null)
{
if(/p/.test(amMatch[0]))
dayHalf = "p";
}

// Remove a|am|p|pm
strTime = strTime.replace(/[a|p|m|:|\s]*/g, "");

// Now we should have nothing left but numbers.
// If the length of the string is 1 or 2,
// then we are dealing with hours only.
if(strTime.length < hour =" strTime;" hour =" strTime.slice(0," minute =" strTime.slice(-2);"> 23)
Hour = Hour % 24;

// Convert the hour and dayhalf.
if(Hour > 12)
{
Hour = Hour - 12;
dayHalf = "p";
}
else if(Hour == 0)
{
Hour = 12;
dayHalf = "a";
}

// This line ensures that the Hour variable is
// converted to a number type so the result
// won't have any preceding zeros.
// ex. "02" would loose the first zero.
Hour *= 1;

// Build our return string
strTime = Hour + ":" + Minute + dayHalf;
return strTime;
}

function TrimStr(str)
{
var sResult = new String(str);
var re1 = /(^\s+)/
var re2 = /(\s+$)/
sResult = sResult.replace (re1, "");
sResult = sResult.replace (re2, "");
return sResult.toString();
}

No comments: