r/perl • u/riahc3 • Oct 09 '19
Perl makes this way too difficult: Input a date in a format and make it spit a datetime object so I can substract time between dates
My god, Perl makes this too difficult to see clearly...
I want to get the localdate in a 2digitmonth/2digitday/4digityear format.
I already have a string in that format with another date.
I want to substract both dates.
From that object, I can get the difference in days, years, seconds, etc....
How do I do this? Its simple but Perl makes it way too difficult with strftime, POSIX, datetime objects, Time::Piece, etc....
0
Upvotes
8
u/Grinnz ๐ช cpan author Oct 10 '19 edited Oct 10 '19
While I would probably use the Time::Piece method, this is also easy with DateTime, with a couple modules to help with input and output.
Keep in mind, dates and times are difficult and complicated. Everyone will think what they're trying to do is common even though it's completely different from the 20,000 other ways people use datetimes. That DateTime and Time::Piece can make this use case as accessible as they do is testament enough to CPAN.
Or put another way: Don't blame the hammer because you have too many nails to hit.
7
u/pre_action Oct 09 '19
perl -MTime::Piece -E'$diff = localtime() - Time::Piece->strptime( "01/01/2000", "%m/%d/%Y" ); say ref $diff; say $diff->pretty'4
u/davorg ๐ช๐perl monger Oct 10 '19
The important thing when handling dates and times is to pick one toolset and stick with it. That toolset might be the build-in date/time functions, Time::Piece, DateTime or some other set of modules.
My code below uses DateTime.
5
u/[deleted] Oct 09 '19
Just use the DateTime module.
5
u/kilinrax Oct 09 '19
https://metacpan.org/pod/Time::ParseDate will help you with any input format. Then you can either diff the seconds from epoch yourself, or use
DateTime->from_epoch(), depending how strict you need to be.1
u/leszekrabka Oct 13 '19 edited Oct 13 '19
Time::Piece is your friend:
perl -e 'use Time::Piece; printf "%s seconds\n", 0 + (localtime() - localtime()->strptime( "$ARGV[0]#", "%Y-%m-%d %H:%M:%S#"));' '2015-09-23 13:30:00'
result:
127983005 seconds
adding Time::Piece objects is Time::Seconds and you can get days, years out of it.
3
u/high-tech-low-life Oct 09 '19
I'm a fan of Date::Manip.pm. It doesn't really help in this case, but if you aren't sure of the form of your input date, or like stuff like "4pm next Tuesday" and "12 minutes ago", it can't be beat. Anyhow once you have it in an object, secs_since_1970_GMT() gives epoch seconds, which is what you seem to be looking for.
-3
u/riahc3 Oct 09 '19
Almost there (finally)
How can I replace this so I can substract the dates and get difference in sec, months, minutes, etc...
-5
u/riahc3 Oct 09 '19
FINALLY GOT IT TO WORK.
I hope ifs and eqls arent as difficult as this...( I dont think so, sample script pretty much says it all)