ruby
ruby

Reputation: 177

How can I display the current date and time, including microseconds?

I need to display the date in the following format in one of my programs:

day - month - year "HH:MM:SS". <microseconds>

I am using Perl 5.8 and I have tried using epoch seconds and converting the time to microseconds like this:

my $epoch = time();
my $time1 = ($epoch - int($epoch)) *1e6

But I am getting this output:

25-05-2016 18:20:20.<incorrect number>

Upvotes: 3

Views: 2376

Answers (2)

ikegami
ikegami

Reputation: 385647

To get what you want,

use POSIX       qw( strftime );
use Time::HiRes qw( time );

my $epoch = time();
my $microsecs = ($epoch - int($epoch)) *1e6;

say strftime("%d-%m-%Y %H:%M:%S", localtime($epoch)) . "." . sprintf("%06.0f", $microsecs);

Output:

25-05-2016 10:50:01.088676

sprintf is used to pad and round to the nearest microsecond.


Alternative:

use POSIX       qw( strftime );
use Time::HiRes qw( gettimeofday );

my ($epoch, $microsecs) = gettimeofday();

say strftime("%d-%m-%Y %H:%M:%S", localtime($epoch)) . "." . sprintf("%06d", $microsecs);

Upvotes: 3

xxfelixxx
xxfelixxx

Reputation: 6592

Use Time::HiRes

Example:

#!/usr/bin/env perl                                                                             

use strict;
use warnings;

use Time::HiRes qw( time );
use DateTime;

for (1..3) {
    my $dt = DateTime->from_epoch( epoch => time() );
    print $dt->strftime("%d-%m-%Y %H:%M:%S.%6N") . "\n";
    sleep 1;
}

Output:

25-05-2016 17:42:16.411722
25-05-2016 17:42:17.414295
25-05-2016 17:42:18.415920

Upvotes: 5

Related Questions