[ale] Need to convert standard time to epoch in bash
Mike Fletcher
fletch at phydeaux.org
Tue Apr 17 12:54:19 EDT 2007
Christopher Fowler wrote:
> Here it is no perl used!
>
> [cfowler at shuttle tmp]$ sh time.sh
> 1176822360
>
> [cfowler at shuttle tmp]$ cat time.sh
> #!/bin/sh
>
> cat >/tmp/ti.c << EOF
> #include <time.h>
>
> int main(int argc, char **argv) {
> struct tm t;
> int ti;
>
> t.tm_mon = atoi(argv[1]) - 1;
> t.tm_mday = atoi(argv[2]);
> t.tm_year = atoi(argv[3]) - 1900;
> t.tm_hour = atoi(argv[4]);
> t.tm_min = atoi(argv[5]);
> t.tm_sec = atoi(argv[6]);
> t.tm_isdst = 1;
>
> ti = mktime(&t);
> printf("%d\n", ti);
>
>
> }
> EOF
>
Ouch. If you're going to drop down into C at least use the standard
library functions . . .
/*
*
* etad -- Reverse output from date(1) into a time_t
*
* gcc -o etad etad.c
*
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main( int argc, char **argv ) {
struct tm *parsed_tm = malloc( sizeof(struct tm) );
time_t epoch_time;
if( argc != 2 ) {
fprintf( stderr, "usage: %s TIME\n", argv[0] );
exit( 1 );
}
if( strptime( argv[1], "%a %b %e %H:%M:%S %Z %Y", parsed_tm ) == NULL ) {
fprintf( stderr, "error parsing time string '%s'\n", argv[1] );
exit( 1 );
}
epoch_time = mktime( parsed_tm );
free( parsed_tm );
fprintf( stdout, "%d\n", epoch_time);
exit( 0 );
}
More information about the Ale
mailing list