- Run this command to display the current date and time:
Get-Date
- Run this command to inspect the DateTime object:
Get-Date | Get-Member
- Notice the Get-Date command produces a System.DateTime object (top of the Get-Member output). It has many intereseting methods and properties.
- Run this command to store the date in a variable:
$now = Get-Date
- Run this command to add 3 days to the current date:
$now.AddDays(3)
- Notice the output should be 3 days in the future.
- Run this command to add 30 days:
$now.AddDays(30)
- Run this command to subtract 10 days:
$now.AddDays(-10)
- Run this command to inspect the DateTime object:
Get-Date | Get-Member
- Notice there are only Add-methods, no Subtract methods.
- Run this command to display the current month:
$now.Month
- Run this command to display the day of the year:
$now.DayOfYear
- Run this command to display the current day of the week:
$now.DayOfWeek
- Run this command to display a short date string:
$now.ToShortDateString()
- Run this command to display the current universal time:
$now.ToUniversalTime()
- Notice any differencse in your local time.
- Run this command to display a long date string:
$now.ToLongTimeString()
In this task we're going to work with different ways to format date output. Since many regions in the world use different date formats, it's recommended to use a standard date format. The ISO 8601 standard is a nice one, because dates and times are arranged so the largest item (the year) is placed to the left and each successively smaller item is placed to the right of the previous item.
- Use a format string to display date and time. This command runs on all versions of PowerShell:
"{0:yyyy}-{0:MM}-{0:dd}T{0:HH}:{0:mm}:{0:ss}" -f (Get-Date)
- Another way to do that would be like this:
"{0:yyyy-MM-dd-HH-mm-ss}" -f (Get-Date)
- Or use the format parameter of Get-Date:
Get-Date -Format s
- And a common way to use in filenames:
"{0:yyyyMMddTHHmmss}" -f (Get-Date)
- or
"{0}" -f (Get-Date -f yyyyMMddTHHmmss)
- Run this command to inspect the contents of the $now variable:
$now
- Run this command to store the current datetime in a new variable:
$later = Get-Date
- Run this command to subtract both objects:
$later - $now
- You get a timespan object.
- Store the timespan object in a variable:
$timespan = $later - $now
- Retrieve several properties from your timespan object:
$timespan.TotalMinutes
is the number of minutes that has elapsed.$timespan.TotalSeconds
is the number of seconds that has elapsed. Notice these two fields exclude each other.