I say Reinstate Monica
I say Reinstate Monica

Reputation: 518

Format string representing hours as H:MM in output

How do I convert the string representing hours to the H:MM format in the same command that outputs the result?

I have this code:

$RunAfterHour = 7
$DelayInMinutes = 10
$RunScriptAfterTime = $RunAfterHour + $DelayInMinutes / 60    # 7:10 AM
"It's after $RunScriptAfterTime"

Which returns:

It's after 7.166666666666667

But I want to format the output as time so it looks like this:

It's after 7:10

I've tried:

"It's after (Get-Date $RunScriptAfterTime -format 't')"
[datetime]::ParseExact($RunScriptAfterTime, 'h.mmmmmmm',$null).ToString('t')

And others but no luck.

Upvotes: 3

Views: 84

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 59031

Since you already have the hour and minutes, you could just format it:

"It's after {0}:{1:D2}" -f $RunAfterHour, $DelayInMinutes

Output:

It's after 7:10

Edit reflecting your comment:

Since you only have the time in hours ($RunScriptAfterTime) you can use the static [timespan]::FromHours method:

$timespan = [timespan]::FromHours($RunScriptAfterTime)
"It's after {0}:{1:D2}" -f $timespan.Hours, $timespan.Minutes

Or altogether:

[timespan]::FromHours($RunScriptAfterTime).ToString('t')

Upvotes: 5

Related Questions