Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Re: Date and time difference

by Marshall (Abbot)
on Nov 19, 2010 at 01:11 UTC ( #872397=note: print w/replies, xml ) Need Help??

in reply to Date and time difference

You example output is a bit different that what you asked for in text. I assume example output is what you want, generate date strings between previous and current...

If you can't install a module, this isn't much code to just roll a couple of simple routines that convert your string format into "epoch seconds" and also convert "epoch seconds" back into your string.

Notes: the $month value is from [0..11] instead of [1..12] to make it easy to use it as an index to look up some text for the month in an array.

If these are local times instead of UTC times, then you will have to consider what happens if the date span includes the daylight savings time switchover. The local versions, ie timelocal and localtime know about DST. And you can figure out if a time is during the DST period by a flag that is returned if you want some special handling of that case. Start with localtime and go from there. However, the DateTime module would make your life easier if you are indeed working in local time - you don't say... See other postings about installing modules. timegm() does know about leap years so that isn't a problem.

The Time::Local module will be installed already.

#!/usr/bin/perl -w use strict; use Time::Local; my $previous = '10111623'; my $current = '10111705'; my $onehour = 60*60; #hour in seconds is 60sec*60min my $cur = date2timegm($previous); my $stop = date2timegm($current); my @result; while ( ($cur+=$onehour) < $stop) { push(@result, timegm2date($cur)); } print join(',',@result),"\n"; #prints: 10111700,10111701,10111702,10111703,10111704 sub timegm2date # returns date string { my $epoch = shift; my ($yr,$mon,$day,$hour) = (gmtime($epoch))[5,4,3,2]; $mon++; $yr+= 1900; $yr = ($yr =~ m/(\d\d)$/)[0]; return (sprintf ("%02d%02d%02d%02d", $yr, $mon, $day, $hour)); } sub date2timegm #returns an epoch time in seconds { my $date = shift; my ($yr,$mon,$day,$hour) = $date =~ m/\d\d/g; --$mon; return (timegm(0,0,$hour,$day,$mon,$yr)); }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://872397]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (8)
As of 2017-09-22 19:52 GMT
Find Nodes?
    Voting Booth?
    During the recent solar eclipse, I:

    Results (268 votes). Check out past polls.