Overview
It is sometimes necessary to let the user input a time and get the corresponding value; I developed a function to scan the text entered by the user and calculate the corresponding value in seconds. The goal is to permit the user to enter text in a handy way and handle it at best.
The function presented here accepts strings like "2h 15m", "2:15:00", "2.15.0", "8100s" and "8100" returning 8100 seconds in all cases.
Description
The function presented here accepts strings formatted in several ways so that the user can choose the one he is more familiar with.
Formats handled by the function are the following:
The function returns -1 in case of errors, mainly if the format is not recognized among the admitted ones
Several check are performed by the function to ensure the string is in the correct format so that the resulting seconds value is correct.
The following notes apply to various formats:
A symmetric function is included in this example that takes a value in seconds and formats it into a string either with colon or "HMS" separators.
All functions are fully commented in the code, so you can understand how they work and which error conditions are checked for.
Steps to Implement or Execute Code
Requirements
Software
Functions have been developed in LabWindows/CVI; no particular version is required
Code makes use of functions from the Formatting and I/O Library, which is part of standard CVI package; no additional library is needed.
Hardware
None
Updates
May 23, 2017
The original version of seconds-to-text function displays negative values as raw number of seconds (e.g. 1 hour negative becomes "-3600s")
Version 2 of the code correctly displays the time in HMS format with a negative sign on the left (e.g. -1000 becomes "-16:40" or "-16m 40s")