Joost Verhelst
Joost Verhelst

Reputation: 85

Adding to a datetime

Forgive me if it's already been asked here somewhere, but I couldn't find it, but here goes.

In a log file I have, there's a time at which the values were logged and the time is written in HH:mm:ss.

I need to parse multiple rows of that file, and so far the only way I can do that it adds a few minutes to the specific time I want to start parsing rows from.

This is the code I currently use to add. However, when the Minute is something like "05" or anything below 10, it just removes the 0 and I end up having a time like this: 15:7:49 while it should be 15:07:49.

When it DOES work and the time doesn't exist in the file, it adds another second. Sometimes the logtool skips a second, but never more than 1.

$a = [datetime]::ParseExact($a,"HH:mm:ss",$null)
$time = [string]$a.Hour + ":" + ($a.Minute+5) + ":" + $a.Second
if ($time -eq $time){$time = [string]$a.Hour + ":" + ($a.Minute+5) + ":" + $a.Second}
else {$time = [string]$a.Hour + ":" + ($a.Minute+5) + ":" + ($a.Second+1)}

Basically, what I'm asking is, how can I add any number to the minute or second, without losing the HH:mm:ss format?

Thanks.

Upvotes: 8

Views: 12660

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

DateTime objects have methods to add seconds, minutes, hours, days, etc.

$a.AddMinutes(5)

The same methods can be used to subtract time from a timestamp by adding a negative value:

$a.AddMinutes(-5)

The output format can be defined e.g. via the ToString() method or the format operator (-f):

$a.ToString('HH:mm:ss')
'{0:HH:mm:ss}' -f $a

However, as Lieven Keersmakers noted in the comments, converting a DateTime value back to a formatted string should be reserved for displaying the value to a user (messages, logging, reports, etc.). In your script DateTime objects are far easier to work with than strings, so you should stick with them as long as possible.

Upvotes: 11

Related Questions