Solved

Convert time (in seconds from 1970) to Datetime Perl/CGI

Posted on 2004-04-16
19
679 Views
Last Modified: 2013-12-25
How to do the above in Perl/CGI?
0
Comment
Question by:dh003756
  • 7
  • 4
  • 3
  • +3
19 Comments
 
LVL 2

Accepted Solution

by:
j_dyer earned 25 total points
ID: 10840463
Something like:

use DateTime;

my $time_thing = 1082105136;
my $dt = DateTime->from_epoch( epoch => time() );  // current time
my $dt1 = DateTime->from_epoch( epoch => $time_thing );   // supplied seconds from 1970


should do the trick (untested code).

0
 
LVL 2

Assisted Solution

by:Fataqui
Fataqui earned 25 total points
ID: 10841128
Hi

You can also use what is in Perl's CORE, by doing so you can format the output in your language or display it in any style you want, DateTime is really a nice package though!

example script ( change the #!/usr/bin/perl -w ) to what your system uses!

#!/usr/bin/perl -w

use strict;

my ( $now, $convert, $version );
# start simple

$now = 1082105136;

$convert = localtime ( $now );

# local time RFC 822 (old)

print $convert . "\n";

# end simple

# start custom

## $version, the type of display to return
## 1 = RFC 822 (old), 2 = valid RFC822

$version = 2;

## $now, in unix seconds since 01/01/70 -> $now = time ();

$now = 1082105136;

## display the time

$convert = time_format ( $version, $now );

print $convert . "\n";

# end custom


sub time_format
{
      my ( $type, $utime ) = @_;

      my @nm = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' );
      my ( $year, $hour, $wday, $mon, $mins, $secs, $mday, $yday, $isdst );
      my @nd = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');

      ( $secs,$mins,$hour,$mday,$mon,$year,$wday,$yday,$isdst ) = localtime ( $utime );

      $year = $year + 1900;
      $wday = $nd[$wday];
      $mon  = $nm[$mon];
      $mday = ( $mday < 10 ? '0' : '' ) . $mday;
      $hour = ( $hour < 10 ? '0' : '' ) . $hour;
      $mins = ( $mins < 10 ? '0' : '' ) . $mins;
      $secs = ( $secs < 10 ? '0' : '' ) . $secs;

      if ( $type == 1 )
      {
            return ( $wday . ' ' . $mon . ' ' . $mday . ' ' . $hour . ':' . $mins . ':' . $secs . ' ' . $year );
      }
      elsif ( $type == 2 )
      {
            return ( $wday . ', ' . $mday . ' ' . $mon . ' ' . $year . ' ' . $hour . ':' . $mins . ':' . $secs );
      }
}

# end script


Fataqui!


0
 

Assisted Solution

by:mannie
mannie earned 25 total points
ID: 10845286
OR use the localtime to convert a date in string form to MS and timelocal to convert a specific date to MS

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =localtime(time);

#and

use Time::Local
#and
$time = timelocal($sec,$min,$hour,$mday,$mon,$year);
0
 
LVL 28

Expert Comment

by:FishMonger
ID: 10848017
0
 
LVL 28

Expert Comment

by:FishMonger
ID: 10848029
Fataqui,

I'd say it's usually it's better to use the Perl modules rather than reinventing the wheel.

2 vs 60+ lines, which would you choose?
0
 
LVL 48

Expert Comment

by:Tintin
ID: 10848564
Fataqui.

I have to comment on your code.

Time and time again, I see stuff like:

     $mday = ( $mday < 10 ? '0' : '' ) . $mday;
     $hour = ( $hour < 10 ? '0' : '' ) . $hour;
     $mins = ( $mins < 10 ? '0' : '' ) . $mins;
     $secs = ( $secs < 10 ? '0' : '' ) . $secs;

There is absolutely no need for this as it can be done using printf/sprintf formats, eg:

$mday = sprintf("%02d",$mday);

or

printf("%02d/%02d/%d\n",$mday,$mon,$year);

Of course the POSIX strfime function is the easiest.
0
 
LVL 1

Expert Comment

by:akashwiz
ID: 10851646
You can use a sub routine. Following script code illustrates it. The result will be something like this:

Mon, 5 Apr 2004 04:32:47

Here is the code:
---------------------


#!/usr/bin/perl
$datentime = do getDate();
print "Content-type: text/html\n\n";
print "$datentime";
exit;

# here starts the sub-routine which  #
# you can use in your own script.     #

sub getDate
{
  local($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) =
    localtime(time());
  local($date);
  $year = (1900+$year);
  $date = do StringWday($wday);
  $date .= ", " . $mday . " " . do StringMonth($mon) . " " . $year . " ";

  if ($hour < 10) {
    $date .= "0" . $hour . ":";
  } else {
    $date .= $hour . ":";
  }

  if ($min < 10) {
    $date .= "0" . $min . ":";
  } else {
    $date .= $min. ":";
  }

  if ($sec < 10) {
    $date .= "0" . $sec;
  } else {
    $date .= $sec;
  }

  return($date);
}

sub StringWday
{
  $wday = $_[0];

  local($string);

  if ($wday == 0) {
    $string = "Sun";
  } elsif ($wday == 1) {
    $string = "Mon";
  } elsif ($wday == 2) {
    $string = "Tue";
  } elsif ($wday == 3) {
    $string = "Wed";
  } elsif ($wday == 4) {
    $string = "Thu";
  } elsif ($wday == 5) {
    $string = "Fri";
  } elsif ($wday == 6) {
    $string = "Sat";
  }

  return($string);
}

sub StringMonth
{
  $mon = $_[0];

  local($string);

  if ($mon == 0) {
    $string .= "Jan";
  } elsif ($mon == 1) {
    $string .= "Feb";
  } elsif ($mon == 2) {
    $string .= "Mar";
  } elsif ($mon == 3) {
    $string .= "Apr";
  } elsif ($mon == 4) {
    $string .= "May";
  } elsif ($mon == 5) {
    $string .= "Jun";
  } elsif ($mon == 6) {
    $string .= "Jul";
  } elsif ($mon == 7) {
    $string .= "Aug";
  } elsif ($mon == 8) {
    $string .= "Sep";
  } elsif ($mon == 9) {
    $string .= "Oct";
  } elsif ($mon == 10) {
    $string .= "Nov";
  } elsif ($mon == 11) {
    $string .= "Dec";
  }
}
0
 
LVL 28

Expert Comment

by:FishMonger
ID: 10851717
It looks like akashwiz and Fataqui don't believe in using modules.  akashwiz, I don't mean to be rude, but do you really believe that your 96 lines of code is a good approach when it can be done in 2 lines using printf or the POSIX module?  Using the POSIX or Date::Time module will give you considerably more options/flexibility in the formatting than your code.  Also, when I ran you code I received several warnings.

Use of "do" to call subroutines is deprecated at c:\testing\akashwiz.pl line 2.
Use of "do" to call subroutines is deprecated at c:\testing\akashwiz.pl line 16.
Use of "do" to call subroutines is deprecated at c:\testing\akashwiz.pl line 17.
Name "main::isdst" used only once: possible typo at c:\testing\akashwiz.pl line 12.
Name "main::yday" used only once: possible typo at c:\testing\akashwiz.pl line 12.
Content-type: text/html

Sat, 17 Apr 2004 19:34:51
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 1

Expert Comment

by:akashwiz
ID: 10851841
I am poor boy FishMonger. I am just a student and I don't have a proper web host so I satisfy all my perl needs through Tripod's free web hosting. They don't provide you will such modules so I am in a habit of doing everything on my own (not depending on any external modules). If someone is lucky enough to have those, I am not against it. Its just that I posted my way of doing it. When you say about your 2 lines of code, why you forget about the 973 lines present in the POSIX module. Calling a external module and calling a in-built sub-routine in my view are more or less same. Besides its a common sense that if you examine at micro level, the script will perform faster if no external module is to be called. And I am 101% sure that the sub-routine is error free as I use it in all my cgi scripts.
 
You can check out the above code in action here:

http://allforms.tripod.com/cgi-bin/datentime.cgi

Its exactly the same code. I copied it from here and uploaded for your satisfaction. Its also present in text form at:

http://allforms.tripod.com/cgi-bin/datentime.txt

Regards

Akash
0
 
LVL 28

Expert Comment

by:FishMonger
ID: 10852183
akashwiz,

It's unfortunate that your hosting service doesn't allow you to have access to the wide verity of modules that are available, but you should, at the very least, have access to some of the standard modules that are installed with Perl (POSIX being one of them).  However, even without them, the code your using can be simplified and reduced.  For example, the StringWday, and StringMonth subs can be made into hashes which would be cleaner, and more efficient.  But if you really want to simplify it and only need numerical date formatting, you can reduce it to 2 lines (as Tintin demonstrated) by using printf, localtime, and time; all three of which are built in to Perl, so you don't need to create a bunch of unnecessary code.  


#!/usr/bin/perl -w

use strict;

my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time());
printf("using 2 lines of code:\n\t%02d/%02d/%d\n\n", $mon+1,$mday,$year+1900);

my %month = (
           0 => 'Jan',
           1 => 'Feb',
           2 => 'Mar',
           3 => 'Apr',
           4 => 'May',
           5 => 'Jun',
           6 => 'Jul',
           7 => 'Aug',
           8 => 'Sep',
           9 => 'Oct',
           10 => 'Nov',
           11 => 'Dec'
          );

printf("added month hash:\n\t%s %02d, %d\n", $month{$mon},$mday,$year+1900);

-- outputs --
using 2 lines of code:
      04/17/2004

added month hash:
      Apr 17, 2004
0
 
LVL 28

Expert Comment

by:FishMonger
ID: 10852198
There are lots of places on the net to get premade Perl scripts.  Some are good, some are so-so, and some are really bad.  Personally, I would not put allforms.tripod.com in the good catagory.
0
 
LVL 28

Expert Comment

by:FishMonger
ID: 10852225
One additional note.  In each of the non-module versions there are 1 or more of the vars that's not being used.  That by itself won't prevent the scripts from running, but Perl should produce a warning message (to STDOUT) for each one of them, assuming you have warnings enabled.
0
 
LVL 1

Expert Comment

by:akashwiz
ID: 10852239
I know the code can be simplified and you are free to do it as it would be benefitial for all. But frankly telling you I am not a expert, just a learner. And I could not understand your comment about allforms.tripod.com. I don't know, on what you commented. On date script or what?
0
 
LVL 48

Expert Comment

by:Tintin
ID: 10852376
akashwiz.

Not wishing to be rude, but as a learner, you'd would be better off not posting code samples in Expert Exchange if you know they are not the most well written routines.

People come to EE to learn from experts.
0
 
LVL 1

Expert Comment

by:akashwiz
ID: 10852810
I really cannot beleive a person like Tintin with top ranking can say that. Before posting my comment on this question, I made sure that I am not breaking any rules of EE. I found the following text.

"It doesn't take a lot to become an expert -- the mere action of commenting in a question makes you one as far as EE is concerned. But it takes a lot to become an Expert, and this page is all about that. Whether it's the points (and seeing your name in the top 15 of a topic area or two) or the pages of answered questions or just the email that says "Good Answer!", the whole point is to help people find out the information they need to resolve a problem."

But don't worry. Neither I have any ambitions to become a expert nor I want to be seen in top 15 list someday. I myself came for help here but saw a question which I thought I knew the answer. I was sure that the answer is right so I posted it. It might be a product of a learner's mind and might not be the best possible answer. You people might be answering questions on this site to gain more n more points but my motive was just to help as I am no where in this points race. But the first expereince trying to help is turned out so bad that I better learn from your advice and stay off. Before I leave I have just one humble line to say to all ""experts"" here.

A tree which is when in its full bloom with loads of fruits hanging all over it, its branches bent down a little.

If you could not get my meaning...no problems.

Bye and best for luck. May god bless you all.....

Akash Pandya
0
 
LVL 28

Expert Comment

by:FishMonger
ID: 10853286
Akash, please don't get upset or feel that we are insulting you.  We are all here to learn from and help each other.  I don't consider myself to be an expert, infact looking back on some of my prior postings, I see that at times I provided some bad code examples.  Most of what I've learned has come from the other people here (such as Tintin, jmcg, ozo and others) that have far more experience and knowledge than I.  There have been times where I've posted 30 or 40 lines of code and then someone else shows how to do the same thing more efficiently and eloquently with only 2 lines.

Ron
0
 
LVL 48

Expert Comment

by:Tintin
ID: 10855420
akashwiz.

I wasn't trying to insult you and I wasn't suggesting that you were breaking an EE rules.

I (and just about everyone else) are happy to help people that post answers where they are learners in that particular field (in fact, we're all learners in every field.  No one can ever say they know it all).

I maybe useful to prefix code samples with a statement of your experience.  That way it helps the questioner to know that while the code may in fact work for them, there may be more efficient ways to approach the problem.

Actually, it's quite useful to see a long handed solution posted, and then a better version posted by people with more experience.  That way, everyone learns.  :-)
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

This article will show, step by step, how to integrate R code into a R Sweave document
Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now