1 /* Seconds to Hour:Minute:Seconds and back
2
3 * Copyright (C) 1998 J.A. Bezemer
4 *
5 * Licensed under the terms of the GNU General Public License.
6 * ABSOLUTELY NO WARRANTY.
7 * See the file `COPYING' in this directory.
8 */
9
10 #include <string.h>
11 #include <stdio.h>
12 #include <math.h>
13
14
15 void
secs2hms(long seconds,char * outstring)16 secs2hms (long seconds, char *outstring) /* 3610 -> 1:00:10 */
17 {
18 sprintf (outstring, "%ld:%02ld:%02ld", seconds / 3600,
19 (seconds / 60) % 60,
20 seconds % 60);
21 }
22
23 void
fsec2hmsf(double seconds,char * outstring)24 fsec2hmsf (double seconds, char *outstring)
25 {
26 double intpart = 0;
27 double floatpart;
28 long i;
29 char helpstring[250];
30
31 floatpart = modf (seconds, &intpart);
32 i = intpart;
33 secs2hms (i, outstring);
34
35 sprintf (helpstring, "%.3f", floatpart);
36 strcat (outstring, helpstring + 1);
37 }
38
39 int
hmsf2fsec(char * instring,double * seconds)40 hmsf2fsec (char *instring, double *seconds)
41 /* returns 0: failure, 1: success; instring will be modified. */
42 {
43 char *charptr;
44 int i = 0;
45
46 if (!strlen (instring))
47 return 0; /* empty string */
48
49 *seconds = 0;
50
51 /* seconds */
52
53 charptr = strrchr (instring, ':');
54 if (charptr == NULL)
55 charptr = instring;
56 else
57 {
58 *charptr = '\0'; /* put a '\0' in place of the ':' */
59 charptr++;
60 }
61 /* charptr is now start of seconds */
62 if (!sscanf (charptr, "%lf", seconds))
63 return 0;
64
65 if (charptr == instring)
66 return 1;
67
68 /* minutes */
69
70 charptr = strrchr (instring, ':');
71 if (charptr == NULL)
72 charptr = instring;
73 else
74 {
75 *charptr = '\0'; /* put a '\0' in place of the ':' */
76 charptr++;
77 }
78 /* charptr is now start of minutes */
79 if (!sscanf (charptr, "%d", &i))
80 return 0;
81 *seconds += i * 60;
82
83 if (charptr == instring)
84 return 1;
85
86 /* hours */
87
88 charptr = strrchr (instring, ':');
89 if (charptr == NULL)
90 charptr = instring;
91 else
92 {
93 *charptr = '\0'; /* put a '\0' in place of the ':' */
94 charptr++;
95 }
96 /* charptr is now start of hours */
97 if (!sscanf (charptr, "%d", &i))
98 return 0;
99 *seconds += i * 3600;
100
101 if (charptr == instring)
102 return 1; /* nothing before hours: OK */
103
104 return 0; /* something before hours. days?? */
105 }
106