If all you wanted to do was get strftime-like behavior while also supporting milliseconds, it would be much easier to simply write a wrapper around stftime, something like this (untested)
The same could be said for your date2sec code. Epoch calculation is not something I think you really want to do. I don't mind you writing your own regexes to extract the appropriate parts from your format, but I would be really suspicious of anyone's hand-rolled epoch second converter. Especially when you have a comment like this:use POSIX 'strftime'; ## similar to strftime but with milliseconds via "%q" sub sec2date { my ($fmt, $sec) = @_; ## fractional part of $sec, rounded to 3 digits my $milli = sprintf "%03.0f", 1000 * ($sec - int $sec); ## %q becomes our milliseconds $fmt =~ s/%q/$milli/g; strftime $fmt, localtime(int $sec); }
"Should be good" ?? Yikes! Instead, I would use Time::Local to do the epoch-seconds conversion part. In your regex, extract the fractional seconds to another variable, send everything to timelocal, and then add on the fractional seconds at the end. Here is how you can use timelocal, even only having year+Julian. You see, it handles all the leap year calculation for you.# convert data2seconds, should be good until the year 2100
Those are my meta-comments about what you're trying to accomplish. As for your code specifically, there are a few things going on that seemed strange to me..use Time::Local 'timelocal_nocheck'; ## given year+julian date, my $epoch = timelocal_nocheck $sec, $min, $hour, $julian, 0, $year-190 +0; ## or given y/m/d (could use normal "timelocal" here) my $epoch = timelocal_nocheck $sec, $min, $hour, $day, $mon-1, $year-1 +900; ## add milliseconds on at the end: $epoch .= ".$milli";
You have this kind of construct several times:
This is written a little more clearly as:$sec = "0" x (2 - length($time)).$time ; $msec = "0" x (3 - length($msec)).$msec ;
You have a zillion lines like this:$sec = sprintf "%02d", $time; $msec = sprintf "%03d", $msec;
Why $format = $format ? Looks like you saw a snippet somewhere that said ($new = $old) =~ s///, but that's completely redundant here as you aren't saving the old value. Better would be:($format = $format ) =~ s/\%Y/$year/g ; # xxxx ($format = $format ) =~ s/\%m/$month/g ; # 1-12 ($format = $format ) =~ s/\%d/$day/g ; # 01-31
But even better yet would be to put all your date information in a hash, and you can replace all those s/// commands with just one:for ($format) { s/%Y/$year/g; s/%m/$month/g; ... }
Update: fixed sprintf format in first code snippetmy %data = ( Y => $year, m => $month, d => $day, ... ); $format =~ s/\%([A-Za-z])/ exists $data{$1} ? $data{$1} : "%$1" /ge;
blokhead
In reply to Re: Wrote my own date parser
by blokhead
in thread Wrote my own date parser
by jeanluca
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |