Jump to content

Time Calculation


David Miller

Recommended Posts

This is a great question. Actually, once you have the time in a JavaScript Date object, doing the adjustment is really easy, and returning it with the FormatDate function is pretty easy too.

 

The hard part is parsing the time in the first place. There's really nothing built into either JavaScript or FusionPro for this. However, the great thing about JavaScript is that just about every problem has already been solved, so a quick Internet search for "JavaScript parse time" turns up several hits, including this one, which I've borrowed here:

String.prototype.reverse = function() {
   var splitext = this.split("");
   var revertext = splitext.reverse();
   var reversed = revertext.join("");
   return reversed;
}

String.prototype.trim = function () {
   return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

/**
* Parse a string that looks like time and return a date object.
* @return  Date object on success, false on error.
*/
String.prototype.parseTime = function() {
   // trim it and reverse it so that the minutes will always be greedy first:
   var value = this.trim().reverse();

   // We need to reverse the string to match the minutes in greedy first, then hours
   var timeParts = value.match(/(a|p)?\s*((\d{2})?:?)(\d{1,2})/i);

   // This didnt match something we know
   if (!timeParts) {
       return false;
   }

   // reverse it:
   timeParts = timeParts.reverse();

   // Reverse the internal parts:
   for( var i = 0; i < timeParts.length; i++ ) {
       timeParts[i] = timeParts[i] === undefined ? '' : timeParts[i].reverse();
   }

   // Parse out the sections:
   var minutes = parseInt(timeParts[1], 10) || 0;
   var hours = parseInt(timeParts[0], 10);
   var afternoon = timeParts[3].toLowerCase() == 'p' ? true : false;

   // If meridian not set, and hours is 12, then assume afternoon.
   afternoon = !timeParts[3] && hours == 12 ? true : afternoon;
   // Anytime the hours are greater than 12, they mean afternoon
   afternoon = hours > 12 ? true : afternoon;
   // Make hours be between 0 and 12:
   hours -= hours > 12 ? 12 : 0;
   // Add 12 if its PM but not noon
   hours += afternoon && hours != 12 ? 12 : 0;
   // Remove 12 for midnight:
   hours -= !afternoon && hours == 12 ? 12 : 0;

   // Check number sanity:
   if( minutes >= 60 || hours >= 24 ) {
       return false;
   }

   // Return a date object with these values set.
   var d = new Date();
   d.setHours(hours);
   d.setMinutes(minutes);
   return d;
}

var time = Field("time").parseTime();
time.setMinutes(time.getMinutes() - 30);
return FormatDate(time, "h:nn A");

You should be able to simply change the data field name in the third-to-last line above to match your data.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...