Skip to content

Instantly share code, notes, and snippets.

@bertrand-lupart
Last active October 18, 2019 07:02
Show Gist options
  • Save bertrand-lupart/e18e2676afbc5d6f3ca12962f06e059c to your computer and use it in GitHub Desktop.
Save bertrand-lupart/e18e2676afbc5d6f3ca12962f06e059c to your computer and use it in GitHub Desktop.
Breaking the 838:59:59 limit of MySQL's SEC_TO_TIME() and TIME_TO_SEC() with Pike
// Breaking the 838:59:59 limit of MySQL's SEC_TO_TIME() and TIME_TO_SEC()
//! @param seconds
//! The number of seconds to convert to time
//! @return
//! Seconds converted to time (123:45:67) as a string, -1 if failed
int|string sec_to_time(int _seconds)
{
int seconds = (int)_seconds;
int h=0, m=0, s=0;
h=seconds/3600;
m=(seconds-(h*3600))/60;
s=(seconds-(h*3600)-(m*60));
// Self-test
// Trading performance for accuracy
if(seconds!=(h*3600+m*60+s))
{
werror("WTF ? %d != %d\n", seconds, (h*3600+m*60+s));
return -1;
}
return sprintf("%02d:%02d:%02d",h,m,s);
}
//! @param time
//! Time to be converted in seconds, as string (123:45:46 or 12:34)
//! @return
//! Seconds as int, -1 otherwise
int time_to_sec(string time)
{
int h=0, m=0, s=0;
int e = 0;
switch(String.count(time,":"))
{
case 2 :
e = sscanf(time, "%d:%d:%d", h, m, s);
if(e!=3)
{
werror("Something went wrong parsing %s (%d %d %d)\n", time, h, m, s);
return -1;
}
break;
case 1 :
e = sscanf("%d:%d", time, m, s);
if(e!=2)
{
werror("Something went wrong parsing %s (%d %d %d)\n", time, h, m ,s);
return -1;
}
break;
default :
werror("Don't know how to parse %s\n", time);
return -1;
}
return h*3600+m*60+s;
}
// Sample use :
// $ pike -M .
// Pike v8.0 release 702 running Hilfe v3.5 (Incremental Pike Frontend)
// > Time.sec_to_time(1234567890);
// (1) Result: "342935:31:30"
// > Time.time_to_sec("342935:31:30");
// (2) Result: 1234567890
@bertrand-lupart
Copy link
Author

bertrand-lupart commented Oct 16, 2019

Pike v8.0 release 702 running Hilfe v3.5 (Incremental Pike Frontend)
> Time.time_to_sec("342935:31:30");
(1) Result: 1234567890
> Time.sec_to_time(1234567890);    
(2) Result: "342935:31:30"

@bertrand-lupart
Copy link
Author

$ pike -M .
Pike v8.0 release 702 running Hilfe v3.5 (Incremental Pike Frontend)
> Time.sec_to_time("1234567890");
(1) Result: "342935:31:30"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment