LabWindows/CVI User Group Documents

cancel
Showing results for 
Search instead for 
Did you mean: 

String-to-Seconds conversion

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:

  • A single value in seconds
  • A string with "HMS" separators, either uppercase or lowercase
  • A string with dots and/or colons

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:

  • When using "HMS" separators is not necessary to use all separators: "1h 10s" is equivalent to "1h 0m 10s"
  • On the other hand, when using colons/dots you must give all relevant values, even if null: "1.10" is one minute, ten seconds, "1.0.10" is 1 hour, 10 seconds; thus, 1 hour must be entered as "1.0.0"
  • A simple value in seconds is not limited to 60: as stated, "8100" string is correctly handled
  • The user cannot mix separators: "1h 10.15" string gives an error

 

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

  1. Add .C and .H files to your project
  2. Simply call the functions! Smiley Wink

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")



Proud to use LW/CVI from 3.1 on.

My contributions to the Developer Community
________________________________________
If I have helped you, why not giving me a kudos?
Download All