I need to get the time in the format "20130808 12:12:12.123"
i.e., "yyyymmdd hour:min:sec.msec"
.
I tried
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$year += 1900;
$mon++;
if ($mon<10){$mon="0$mon"}
if ($mday<10){$mday="0$mday"}
if ($hour<10){$hour="0$hour"}
if ($min<10){$min="0$min"}
if ($sec<10){$sec="0$sec"} but this doesn't provide the `msec` as a part of time.
How can i do that ?
In Perl if you want to calculate time in milliseconds (thousandths of a second) you can use Time::HiRes and the time() function.
You can use the POSIX function strftime() in Perl to format the date and time with the help of the following table. Please note that the specifiers marked with an asterisk (*) are locale-dependent. Specifier. Replaced by. Example.
Timestamp can be created by creating a DateTime object and then calling the now constructor. my $datetime = DateTime->now; print "$datetime\n" ; A DateTime object can also be created by providing all the details part wise like date, hour, minute, second, etc.
Here's a complete script. As proposed before, it is using Time::HiRes::time
for microsecond support, and it's also using POSIX::strftime
for easier formatting. Unfortunately strftime
cannot deal with microseconds, so this has to be added manually.
use Time::HiRes qw(time);
use POSIX qw(strftime);
my $t = time;
my $date = strftime "%Y%m%d %H:%M:%S", localtime $t;
$date .= sprintf ".%03d", ($t-int($t))*1000; # without rounding
print $date, "\n";
If you don't mind to use a CPAN module, then I would propose the excellent Time::Moment module:
use Time::Moment;
print Time::Moment->now->strftime("%Y%m%d %T%3f"), "\n";
And if it may be formatted as an ISO8601 date including a time zone offset and microseconds instead of milliseconds, then it's simply:
print Time::Moment->now->to_string, "\n";
use Time::HiRes
Looking at this briefly, it can provide milliseconds since epoch fairly easily but didn't seem to extend localtime(), so there's probably a bit of work involved in using it in a full calendar context.
Here's a working example:
use strict;
use warnings;
use Time::Format qw/%time/;
use Time::HiRes qw/gettimeofday/;
my $time = gettimeofday; # Returns ssssssssss.uuuuuu in scalar context
print qq|$time{'yyyymmdd hh:mm:ss.mmm', $time}\n|;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With