Operating System - HP-UX
1833323 Members
2706 Online
110051 Solutions
New Discussion

Converting 'date' to Epoch

 
SOLVED
Go to solution
Joel Shank
Valued Contributor

Converting 'date' to Epoch

Can anyone tell me how to convert a standard UNIX date to a timestamp (seconds from Epoch).

I know I can use time() to get the current Epoch, but I want to compute Epoch for ANY entered date.

Thanks for your assistance,
jls
6 REPLIES 6
S.K. Chan
Honored Contributor

Re: Converting 'date' to Epoch

Joel Shank
Valued Contributor

Re: Converting 'date' to Epoch

Thanks, but that was my question on converting Epoch to a date/time. Now what I need is the reverse, take any date-format and convert it to Epoch.
Robin Wakefield
Honored Contributor
Solution

Re: Converting 'date' to Epoch

Hi Joel,

This is one way of doing it, using perl & local timezones:

============================================
#!/opt/perl5/bin/perl

use Time::Local;
my %months=qw(Jan 0 Feb 1 Mar 2 Apr 3 May 4 Jun 5 Jul 6 Aug 7 Sep 8 Oct 9 Nov 10 Dec 11);
my %days=qw(Sun 0 Mon 1 Tue 2 Wed 3 Thu 4 Fri 5 Sat 6);

my ($hour,$min,$sec)=split ':',$ARGV[3];
my $day=$days{$ARGV[0]};
my $month=$months{$ARGV[1]};
my $mday=$ARGV[2];
my $year=$ARGV[4]-1900;

my $time=timelocal($sec,$min,$hour,$mday,$month,$year);
print "$time\n";
===========================================

So, to run it, you'd use:

./date2epoch.pl Thu Feb 28 16:09:55 2002
1014912595

Rgds, Robin.
Joel Shank
Valued Contributor

Re: Converting 'date' to Epoch

Thank you Robin.

That will work. Do you know how I can do this in C? I'd really like to make this more portable.

jls
Robin Wakefield
Honored Contributor

Re: Converting 'date' to Epoch

Hi Joel,

Here goes:

====================================
/*

Convert date to epoch time

*/

#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);
}
========================================

Now create a file containing "%c", say, /tmp/datemsk

and then:

export DATEMSK=/tmp/datemsk

Compile your program, then run it:

# ./a.out "`date "+%c"`"
1014914858

the file contains the date format that you wish to use (man getdate).

Rgds, Robin.
Joel Shank
Valued Contributor

Re: Converting 'date' to Epoch

Robin:

Thank you so much. This is EXACTLY what I was looking for!

jls