Operating System - HP-UX
1820638 Members
1965 Online
109626 Solutions
New Discussion юеВ

convert human date to epoch

 
SOLVED
Go to solution
Tim Nelson
Honored Contributor

convert human date to epoch

I see an number of references in here of using C to convert a supplied argument from epoch to a human date but how about human date to epoch ? Looks like the ctime source should do it but I just can't seem to get it ..

Below is the source for the epoch to human. Could someone elaborate for the reverse ?

#include
int main(argc, argv)
int argc;
char **argv;
{
time_t t=strtoul(argv[1], NULL, 0);
printf("%s", ctime(&t));
}
4 REPLIES 4
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: convert human date to epoch

Hi Tim:

The function you are looking for is 'mktime'.

I've attached a small example program that first gets the current time, displays it's epoch seconds and Year,Month,Day,Hr,Min, and Second. It then adds 1 to to day and calls mktime to get a new epoch seconds 1 day (86400 seconds later).

That should be good enough to get you started.

By the way, the stuff is really easy to do in both directions in Perl.
If it ain't broke, I can fix that.
Mike Hassell
Respected Contributor

Re: convert human date to epoch

Tim,

The GNU date command supports output of epoch, which I find to be rather useful if you need to convert the current time/date stamp to epoch. Of course this only helps if you're trying to convert the current time/date stamp, rather than a supplied human date -> epoch.

You can download a precompiled version of GNU date here:

http://hpux.connect.org.uk/hppd/hpux/Gnu/sh_utils-2.0/

syntax:

date +%s

Hope that helps.

-Mike
The network is the computer, yeah I stole it from Sun, so what?
Craig Rants
Honored Contributor

Re: convert human date to epoch

Also, the perl option

/usr/contrib/bin/perl -e "print time"

GL,
C
"In theory, there is no difference between theory and practice. But, in practice, there is. " Jan L.A. van de Snepscheut
Tim Nelson
Honored Contributor

Re: convert human date to epoch

Thanks again to all.. THe below seems to work the best.
#include
#include
#include
#include
#include

#define FALSE 0
#define TRUE 1

int main(argc,argv)
int argc;
char *argv[];

{
struct tm *dateptr;
time_t date;
int do_exit=FALSE;

if (argc != 2) {
fprintf(stderr, "Usage: %s \n", argv[0]);
exit(1);
}


/* Convert date */
dateptr = getdate(argv[1]);
if (getdate_err != 0) {
fprintf(stderr, "%s: Could not interpret %s. Error = %d\n", argv[0], argv[1], getdate_err);
exit(1);
}

date = mktime(dateptr);
if (date == -1) {
fprintf(stderr, "Could not \"mktime\" for date, errno=%d\n", errno);
exit(1);
}

printf("%d\n", date);

exit(0);
}