Converting date to UTC ( Universal Time) is useful while working with dates from different time zones or handling datetime values in a standardized format.
Use the ToUniversalTime() method of the Get-Date cmdlet to convert a local date and time to UTC format.
In this article, we will discuss how to convert local date and time to UTC, formatting the UTC date and time output.
PowerShell Convert Date Time to UTC
To convert a current date and time of the system to UTC using PowerShell, use the Get-Date cmdlet with its ToUniversalTime() method.
$currentDate = Get-Date $utcDate = $currentDate.ToUniversalTime()
In the above PowerShell script, the Get-Date cmdlet retrieves the current date and time and stores it in the $currentDate
variable. Then, it uses the ToUniversalTime()
method to convert the current local date time to UTC.
The output of the above PowerShell scripts converts the local system date time to UTC.
Convert the Date to UTC and Format the UTC Date Time Output
To convert the date to UTC and format the UTC date and time to a customized date format, use the ToString() method.
$dateFormat = "yyyy-MM-dd HH:mm:ss" $utcFormatDate = $utcDate.ToString($dateFormat) $utcFormatDate
The output of the above PowerShell script converts the UTC date and time to the customized date format.
PS C:\> $currentDate = Get-Date PS C:\> $utcDate = $currentDate.ToUniversalTime() PS C:\> $utcDate
09 April 2023 18:16:59
PS C:\> $dateFormat = "yyyy-MM-dd HH:mm:ss" PS C:\> $utcFormatDate = $utcDate.ToString($dateFormat)
PS C:\> $utcFormatDate 2023-04-09 18:16:59
PS C:\>
Conclusion
I hope the above article on how to convert date and time to UTC using the ToUniversalTime() method is helpful to you.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.