Set 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.

# ---------------------------------------------------------------
# Adapted from VBScript code contained in the book:
#      "Windows Server Cookbook" by Robbie Allen
# ISBN: 0-596-00633-0
# ---------------------------------------------------------------
use Win32::OLE;
$Win32::OLE::Warn = 3;

print 'Current time: ' . VBS::Now(), "\n";

$strCommand = 'cmd.exe /c time 23:02:00';
$objWshShell = Win32::OLE->new('WScript.Shell');
$intRC = $objWshShell->Run($strCommand, 0, 1);
if ($intRC != 0) {
    print 'Error returned from time command: ' . $intRC, "\n";
}
else {
    print "time command completed successfully\n";
}

$strCommand = 'cmd.exe /c date 11/01/2004';
$intRC = $objWshShell->Run($strCommand, 0, 1);
if ($intRC != 0) {
    print 'Error returned from date command: ' . $intRC, "\n";
}
else {
    print "date command completed successfully\n";
}

print 'New time: ' . VBS::Now(), "\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 1971 times.

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