Display datetime (Perl)

This code can be found in Chapter 2 of Windows Server Cookbook

Purchase XP Cookbook or Networking Recipes for only $25 plus shipping! While supplies last.

Find out how to download all of the Perl code from this site.

# This code displays the local date, time and time zone on a target computer
# ---------------------------------------------------------------
# Adapted from VBScript code contained in the book:
#      "Windows Server Cookbook" by Robbie Allen
# ISBN: 0-596-00633-0
# ---------------------------------------------------------------

use Win32::OLE qw(in);
$Win32::OLE::Warn = 3;

# ------ SCRIPT CONFIGURATION ------
$strComputer = '.';
# e.g. rallen-srv01
# ------ END CONFIGURATION ---------
print "Current time using Now function: \n";
print "\t", VBS::Now(), "\n";

$dicDaysOfWeek = Win32::OLE->new('Scripting.Dictionary');
$dicDaysOfWeek->Add(0, 'Sun');
$dicDaysOfWeek->Add(1, 'Mon');
$dicDaysOfWeek->Add(2, 'Tue');
$dicDaysOfWeek->Add(3, 'Wed');
$dicDaysOfWeek->Add(4, 'Thu');
$dicDaysOfWeek->Add(5, 'Fri');
$dicDaysOfWeek->Add(6, 'Sat');

$objWMI = Win32::OLE->GetObject('winmgmts:\\\\' . $strComputer . '\\root\\cimv2');
$objDateTime = $objWMI->Get('Win32_Localtime=@');
print "Current time using WMI: \n";
print "\t", $dicDaysOfWeek->Item($objDateTime->DayOfWeek),' ',$objDateTime->Month, '/', $objDateTime->Day, '/',$objDateTime->Year,' ',$objDateTime->Hour,':',$objDateTime->Minute, "\n";
print "Time zone:\n";
$colTZ = $objWMI->ExecQuery('select * from Win32_TimeZone');
foreach my $objTZ (in $colTZ) {
    print "\t",$objTZ->Caption, "\n";
}

package VBS;
use strict;

use Win32::OLE::NLS qw(:TIME
		       :DATE
		       GetLocaleInfo GetUserDefaultLCID
                       LOCALE_SMONTHNAME1 LOCALE_SABBREVMONTHNAME1
                       LOCALE_SDAYNAME1 LOCALE_SABBREVDAYNAME1
		       LOCALE_IFIRSTDAYOFWEEK
		       LOCALE_SDATE LOCALE_IDATE
		       LOCALE_SGROUPING
		       );
use Win32::OLE::Variant;

use constant EPOCH       => 25569;
use constant SEC_PER_DAY => 86400;

our $lcid;
BEGIN {
    $lcid = GetUserDefaultLCID();
    Win32::OLE->Option(LCID => $lcid);
}

# Return the local time in seconds since the epoch.
sub _localtime_in_sec {
    require Time::Local;
    return 2.0 * CORE::time() - Time::Local::timelocal(gmtime);
}

# Extract specific information out of a date.
sub _extract_from_date {
    my($date,$method,$format) = @_;
    return unless $date;
    unless (UNIVERSAL::isa($date, "Win32::OLE::Variant")) {
        $date = Variant(VT_DATE, $date);
    }
    return $date->$method($format, $lcid);
}

# Returns the current date and time according to the setting of your
# computer's system date and time.
sub Now {
    return Variant(VT_DATE, EPOCH + _localtime_in_sec()/SEC_PER_DAY);
}

This code has been viewed 2884 times.

New from the creators of TechTasks.com: StatSheet.com