How to Convert Time as "HH:MM:SS" to a Numeric Value

Last reviewed: April 29, 1996
Article ID: Q101796
The information in this article applies to:
  • Microsoft FoxPro for MS-DOS, versions 2.0, 2.5, and 2.5a
  • Microsoft FoxPro for Windows, versions 2.5 and 2.5a

To convert a time string of the form "HH:MM:SS" to a numeric value, you must create a user-defined function (UDF). The following code is provided as an example.

   * TTON(<expC>)
   * Convert <expC> to a number of hours
   * Return value - Numeric
   * <expC> is a string of the form "HH:MM:SS". If <expC> doesn't
   * contain two colons (::), or time values are not in the range,
   * TTON returns -1.

   FUNCTION TTON
   PARAMETERS timestr
   PRIVATE pos1,pos2,hours,minutes,seconds

   * Get position of first and second occurrences of ':'
   pos1=at(':',timestr,1)
   pos2=at(':',timestr,2)

   * Error checking
   IF pos1==0 OR pos2==0
      RETURN -1
   ENDIF

   * Convert hh, mm and ss to numeric values and check for valid range
   hours = VAL(timestr)
   IF hours < 0 or hours > 24
      RETURN -1
   ENDIF
   minutes = VAL(SUBSTR(timestr,pos1+1))   && from 1st ':' to 2nd ':'
   IF minutes < 0 or minutes > 59
      RETURN -1
   ENDIF
   seconds=VAL(SUBSTR(timestr,IIF(LEN(timestr)>=pos2+1,pos2+1,0)))
   IF seconds < 0 or seconds > 59
      RETURN -1
   ENDIF

   * Convert minutes and seconds to decimal values
   minutes=minutes/60
   seconds=(seconds/60)/60

   * Return total value of hours, minutes and seconds
   RETURN ( hours+minutes+seconds )


Additional reference words: FoxWin FoxDos 2.00 2.50 2.50a NTOT
KBCategory: kbprg
KBSubcategory: FxprgGeneral


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: April 29, 1996
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.