Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Getting started with DateTime

by snax (Hermit)
on Oct 15, 2017 at 16:07 UTC ( [id://1201402]=note: print w/replies, xml ) Need Help??


in reply to Getting started with DateTime

Great stuff!

It's a dozen plus years after this was written and it's still useful. There's a subtle bit introduced at the very end that should maybe be emphasized: these are DateTime objects we're dealing with, and the scalar variables are references to the underlying object, which can lead to some confusion if you let that fact slip your mind.

Consider the bit about math with dates at the end:

my $dt1 = DateTime->now(); my $dt2 = $dt1->clone->subtract( weeks => 1);

Miss the ->clone bit and you've got two references to the same DateTime object, one week subtracted from the original $dt1 value. Probably not what you had in mind.

Imagine expecting the following to DWIM:

#!/usr/bin/perl -w use strict; use DateTime; my ($start, $end, @dates); $start = DateTime->new(day => 1, month => 1, year => 2017); $end = DateTime->new(day => 31, month => 1, year => 2017); while ($start <= $end) { # Skip weekends if ($start->day_of_week() > 5) { push(@dates, $start); } $start = $start->add(days => 1); } for (@dates) { print $_, $/; }

See it? I've forgotten to clone my $start variable as I push it onto my stack. This code produces:

2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00 2017-02-01T00:00:00

All I needed to do was push(@dates, $start->clone()); and then I see what I meant:

2017-01-02T00:00:00 2017-01-03T00:00:00 2017-01-04T00:00:00 2017-01-05T00:00:00 2017-01-06T00:00:00 2017-01-09T00:00:00 2017-01-10T00:00:00 2017-01-11T00:00:00 2017-01-12T00:00:00 2017-01-13T00:00:00 2017-01-16T00:00:00 2017-01-17T00:00:00 2017-01-18T00:00:00 2017-01-19T00:00:00 2017-01-20T00:00:00 2017-01-23T00:00:00 2017-01-24T00:00:00 2017-01-25T00:00:00 2017-01-26T00:00:00 2017-01-27T00:00:00 2017-01-30T00:00:00 2017-01-31T00:00:00

I hope this helps someone else avoid a similar problem in the future -- even a dozen years from now :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1201402]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-04-19 01:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found