How to use the command Get-Date (with examples)
- Windows
- December 25, 2023
The Get-Date
command is a PowerShell cmdlet that retrieves the current date and time. It can be used to display the current local date and time as well as perform various operations on dates and times.
Use case 1: Display the current date and time
Code:
Get-Date
Motivation: You may want to quickly check the current date and time in your PowerShell session. This can be useful for various tasks such as tracking execution times or for general reference.
Explanation: This command simply retrieves the current date and time using the default settings.
Example output:
Friday, March 26, 2021 6:17:32 PM
Use case 2: Display the current date and time with a .NET format specifier
Code:
Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Motivation: Sometimes, you may need to display the current date and time in a specific format for your scripts or reports. By using .NET format specifiers, you have more control over the output format.
Explanation: The -Format
parameter is used to specify a custom format for the date and time. In this example, we use the format specifier “yyyy-MM-dd HH:mm:ss” to display the date and time in the format “YYYY-MM-DD HH:MM:SS”.
Example output:
2021-03-26 18:17:32
Use case 3: Display the current date and time in UTC and ISO 8601 format
Code:
(Get-Date).ToUniversalTime()
Motivation: If you need to work with UTC dates or want to convert the local date and time to UTC format, this command can be useful.
Explanation: The ToUniversalTime()
method is used to convert the current date and time to UTC format. The (Get-Date)
command retrieves the current local date and time, and then the ToUniversalTime()
method converts it to UTC.
Example output:
Friday, March 26, 2021 1:17:32 PM
Use case 4: Convert a Unix timestamp
Code:
Get-Date -UnixTimeSeconds 1577836800
Motivation: Unix timestamps are often used to represent dates and times in a numerical format. If you have a Unix timestamp and want to convert it to a more readable format, you can use this command.
Explanation: The -UnixTimeSeconds
parameter is used to specify a Unix timestamp value. In this example, we provide the Unix timestamp 1577836800
which corresponds to the date and time January 1, 2020 00:00:00 UTC.
Example output:
Wednesday, January 1, 2020 12:00:00 AM
Conclusion:
The Get-Date
command is a powerful tool for retrieving and manipulating date and time information in PowerShell. Whether you need to display the current date and time, format it in a specific way, convert it to UTC, or work with Unix timestamps, this command provides the necessary functionality. Take advantage of these use cases to enhance your PowerShell scripts and automate date/time-related tasks.