How do I work with non date-specific time in a variable

I have searched all over God’s half internet-acre and can’t find an answer.

I need to have a variable representing 1:00am. Date does not matter.

Next, I want to increment it by five minutes - i.e. make the variable 1:05 am

How the heck do I do that? Everything I find wants to run Get-Date and do stuff with the results. Not what I need

Help, please

—B

You should share your code so we can see exactly what you are doing. Also - providing context helps paint us a picture of why you are doing and what problem you are solving, so you should share that too in future posts.

Date Time objects have methods to add/remove time. Given you are working with time, whatever you are dealing with probably shoudl be a date/time object. The reason you search and it says Get-Date as that’s how powershell can easily generate date time objects.

$Date = Get-Date -Hour 1 -Minute 0 -Second 0 
$NewDate = $Date.AddMinutes(5)
$NewDate

if you just use a string, how does powershell know to format it properly? You can always pull the data and format it how you want in the end.

2 Likes
$Date = Get-Date -Hour 1 -Minute 0 -Second 0
# Then to increment
$Date.AddMinutes(5)

Heh I was too slow

2 Likes

interesting. I hadn’t ever thought about the fact that there isn’t a time-specific object type. But I think maybe you can use the regular DateTime object and just ignore the date part of it?
Using your example.

$Time = Get-Date "1:00 am"
$Time
$Time.ToShortTimeString()

now we’ve got a DateTime object that represents 1:00am today and we’ve got a method for returning just the “1:00 am” part in a string format we want.
If I want to increment it I can redefine it and use the AddMinutes method

$Time = $Time.AddMinutes(5)
$Time.ToShortTimeString()
1 Like

Great solution here while even providing the correct format with the ToShortTimeString function.

$time = (Get-date '01:00').ToString('h:mm tt').ToLower()
$newTime = (Get-Date $time).AddMinutes(5).ToString('h:mm tt').ToLower()

Thanks everyone! Looks like Grey0ut’s solution works best for my application. Now to figure out how to get a scheduled task working

Off to a new post!

—K