[ale] Need to convert standard time to epoch in bash

Jeff Lightner jlightner at water.com
Tue Apr 17 12:59:16 EDT 2007


Is the issue that you don't want to write a full perl script or that you
don't have perl at all?

If it is the former you can do a one line command within your bash
script:
perl -e 'print scalar localtime $ARGV[0];print "\n"' <epoch time>

BTW - The date '+%s' gives epoch from date not vice-versa.

-----Original Message-----
From: ale-bounces at ale.org [mailto:ale-bounces at ale.org] On Behalf Of Mike
To: ale at ale.org
Fletcher
Sent: Tuesday, April 17, 2007 12:54 PM
To: Atlanta Linux Enthusiasts
Subject: Re: [ale] Need to convert standard time to epoch in bash

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 );
}
_______________________________________________
Ale mailing list
Ale at ale.org
http://www.ale.org/mailman/listinfo/ale



More information about the Ale mailing list