This post will present several methods to resolve the stated query.
How to Format Date and Time in PowerShell?
The date and time can be formatted in different formats using “-Format”, “-UFormat”, and “-DisplayHint” specifiers.
Check out the provided examples to view the time and date in numerous formats.
Example 1: Get the Current Data and Time
Execute the given “Get-Date” cmdlet to print the current time and date:
Example 2: Get Only Time Using the “-DisplayHint” Specifier
Now, add the “-DisplayHint” specifier to format the time only:
Example 3: Get Only Date Using the “-DisplayHint” Specifier
Similarly, use the “-DisplayHint” specifier to display the date only:
Example 4: Use the “.Net” Specifier to Format DateTime
In this example code, we will format the date and time using the “.Net” specifier:
The above example demonstrated the formation of time and date.
Example 5: Use the “-UFormat” Specifier to Format the DateTime
Using the “-UFormat” specifier, we will format the date and time as follows:
Example 6: Get All the DateTime Formats
In order to retrieve all the formats of the date and time, execute the given line of code:
The above command will first fetch the current date and then display the relevant date and time in different formats:
To get the value in a specified format, add the index number as follows:
Example 7: Print Date and Time Using the “-Format” Specifier
Write and execute the given command to format the time only using the “-Format” specifier:
Example 8: Print Only Date Using the “-Format” Specifier
Now, only format the current date using the “-Format” specifier:
Example 9: Convert the Date and Time to String Format
To convert date and time to string execute the given command:
Here, the “Get-Date” method will fetch the current date, and the “ToString” method will convert it into the given format:
Example 10: Get the Day Number of the Year
Execute the given command to get the day of the year specified by the user:
That was all about the different approaches to format date and time in PowerShell.
Conclusion
Date and time can be retrieved using the “Get-Date” cmdlet. Moreover, the Date and Time can be formatted in PowerShell using several specifiers, such as “-Format”, “-UFormat”, or “-DisplayHint”. These format specifiers are used alongside the “Get-Date” cmdlet to format the date and time. This post has elaborated a complete procedure to format the date and time.