resolver101
resolver101

Reputation: 2255

Setting the time of a System.DateTime object in PowerShell

I wish to set the System.DateTime object below with the time from $time:

$CurrentTime = (date)
$Time = "9:00"

How do I get the date from $CurrentTime, but with hours, minutes, seconds from $time?

Upvotes: 2

Views: 16011

Answers (4)

$CurrentTime = Get-Date -Hour "09" -Minute "00" -Second "00"

Upvotes: 1

Tomas Panik
Tomas Panik

Reputation: 4629

This should work:

$CurrentTime = [System.DateTime]::Parse((date).ToString("yyyy.MM.dd"))
$Time = [System.Timespan]::Parse("9:00")
$Result = $CurrentTime.Add($Time)

Upvotes: 1

Shay Levy
Shay Levy

Reputation: 126932

Get-Date -Year $CurrentTime.Year `
         -Month $CurrentTime.Month `
         -Day $CurrentTime.Day `
         -Hour $time.split(':')[0] `
         -Minute $time.split(':')[-1]
         -Second $time.split(':')[-1]

Upvotes: 1

jon Z
jon Z

Reputation: 16646

Try this:

[datetime]::ParseExact("09:00","hh:mm",$null)

Upvotes: 8

Related Questions