What is the best way to convert --> Mar 11 10:29:47 2021 GMT <-- into epoch on multiple platforms. Date::Parse module is not available by default on all platforms.
Asked
Active
Viewed 353 times
-4
-
Regular expressions can only help you in matching all or parts of a date string from a context, but you'd still have to implement the logic to convert what you matched into a UNIX timestamp. Quite a number of languages have some form of date string to date object/timestamp functionality; you'll have to use that specifically for each scenario. – oriberu Mar 28 '20 at 07:15
1 Answers
3
Use the strptime()
("string parse time") method from Time::Piece which has been a part of the standard Perl distribution since 5.10.0 in 2007.
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use Time::Piece;
my $str = 'Mar 11 10:29:47 2021 GMT';
my $fmt = '%b %d %H:%M:%S %Y %Z';
my $date = Time::Piece->strptime($str, $fmt);
say $date->epoch; # prints 1615458587
strptime
is a standard Unix tool which is available in many forms. You can get more information about the format strings that it uses from its manual page.

Dave Cross
- 68,119
- 3
- 51
- 97