soMuch2Learn
soMuch2Learn

Reputation: 187

Powershell: Change date to int?

I have a cmdlet that is expecting an int32 for the date instead of a normalized input.

Set-CTXGroupPolicyConfiguration, RebootScheduleStartDate wants int32-input. For instance, if i enter this into policy manually, it has tomorrow, 1/18/2015 as 132055314. Coming up blank with what that number is even referring to.

Upvotes: 2

Views: 14429

Answers (3)

NewSites
NewSites

Reputation: 1739

I don't understand why the previous answers are so complicated. Why not just:

$nTicksPerDay = 1e7 * 60 * 60 * 24
$nDate = [int](((get-date).ticks) / $nTicksPerDay)

On Aug. 1, 2023, that gives $nDate = 738,732. Since

2,023 * 365 + 7 * 30 = 738,605

I presume that with adjustments for leap years and the actual number of days before Aug. 1, $nDate is the correct number of days since Jan. 1, 0001.

Upvotes: 1

Gryyphyn
Gryyphyn

Reputation: 31

I know this is a ridiculously old post but it's the top response on Google for "powershell get-date as int".

$DateInt = [Int]((Get-Date).addDays(-100).ToString('yyyyMMdd'))

Upvotes: 3

Frode F.
Frode F.

Reputation: 54841

This was fun. I found this Citrix Support site where they describe how the dates are stored as a dword (uint32) value in registry. The dword-value is created like:

  1. Date is split into year, month and date
  2. Each value is converted to hex-value
  3. The hex-values are combined (16bit year, 8bit month, 8bit day) in the pattern yyyyMMdd
  4. The combined hex-value is converted to decimal

I've created a couple of functions to convert the dates for you:

function ConvertFrom-DwordDate([int32]$DwordValue) {
    #Ex. $DwordValue = 132055314
    #Convert to hex with 8 chars (16bit year + 8bit month + 8bit day)
    $hex = $DwordValue.ToString('X8')
    #Ex. $hex = 0x07df0112 = 0x07df(year) 0x01 (month) 0x12 (day)

    #Convert to date string
    $datestring = '{0:D4}\{1:D2}\{2:D2}' -f [convert]::ToUInt32($hex.Substring(0,4),16), [convert]::ToUInt32($hex.Substring(4,2),16), [convert]::ToUInt32($hex.Substring(6,2),16)
    #Convert to datetime and output
    $datetime = [datetime]::ParseExact($datestring,'yyyy\\MM\\dd',$null)
    #Output
    $datetime
}

function ConvertTo-DwordDate([datetime]$Date) {
    #Convert to combined hex
    $combinedhex = '{0:X}{1:X2}{2:X2}' -f $Date.Year, $Date.Month, $Date.Day
    #Convert to decimal
    $decimal = [convert]::ToUInt32($combinedhex,16)
    #Ouput
    $decimal
} 

ConvertTo-DwordDate -Date (Get-Date).AddDays(1)
132055314

ConvertFrom-DwordDate -DwordValue 132055314

søndag 18. januar 2015 00.00.00

Upvotes: 7

Related Questions