≡ Menu

PowerShell: How to query date time without seconds

How many times you got a need for querying the date time variable using Get-Date or [DateTime]:Now but without seconds value in it or making it as 00 seconds? Let us find out what are the options to achieve this using PowerShell.

By default Get-Date cmdlet gives seconds as well. In some cases we feel reading till minutes is sufficient or we want to round off to 00 seconds. This is possible if you decide to convert time value to a string as shown below.

$datetime = Get-Date -Format “yyyyMMddHHmm”

[datetime]::ParseExact($datetime,“yyyyMMddHHmm”,$null)

While this is good, I was looking for better approaches to do this without actually converting it to a string. Lucky I came across one.

This approach is simple which deducts seconds from current date time value to make it zero.

$datetime = Get-Date

$datetime.AddSeconds($datetime.Second)

date-time-without-seconds

Hope you liked it.

Comments on this entry are closed.

  • Nilton February 24, 2017, 2:57 pm

    I found an alternative:

    Get-Date -Date (Get-Date -Format “yyyy-MM-dd”)

    The -Format just returns those values, which means -Date will set all other time values to 0

    This also does not require a temporal variable. The exact same as the example in the article:

    Get-Date -Date (Get-Date -Format “yyyy-MM-dd hh:mm”)

    • Wintel Rocks February 25, 2017, 11:05 am

      Hi Nilton,

      Thanks for sharing your approach. Appreciate that.

  • John wick May 29, 2019, 2:57 pm

    Hi

    I really appreciate your solution of subtract seconds, thanks!