PowerShell Get-Date: Everything You Need to Know!

PowerShell Get-Date

PowerShell is a powerful scripting language that allows you to automate tasks and manage your computer system efficiently. One of the most useful commands in PowerShell is Get-Date, which allows users to retrieve the current date and time, as well as perform various calculations and transformations on dates and times. In this comprehensive guide, I will take you through everything you need to know about mastering PowerShell Get-Date.

Introduction to PowerShell Get-Date

PowerShell Get-Date

Before we delve into using the Get-Date cmdlet, let’s first understand the DateTime object in PowerShell. The DateTime object represents a specific date and time and is used to perform various date and time operations in PowerShell. You can retrieve the current date and time using the Get-Date cmdlet. By default, it will display the date and time in the format of the local computer.

The syntax for Get-Date cmdlet is as follows:

Get-Date
   [[-Date] <DateTime>]
   [-Year <Int32>]
   [-Month <Int32>]
   [-Day <Int32>]
   [-Hour <Int32>]
   [-Minute <Int32>]
   [-Second <Int32>]
   [-Millisecond <Int32>]
   [-DisplayHint <DisplayHintType>]
   [-UFormat <String>]
   [-Format <String>]
   [<CommonParameters>]

Here’s a basic example:

 Get-Date

The cmdlet returns a DateTime object in long-date long-time formats, which can be formatted and manipulated using other PowerShell cmdlets. The DateTime object has several properties, including Year, Month, Day, Hour, Minute, Second, and Millisecond, among others. These properties can be accessed and manipulated using other PowerShell cmdlets.

PowerShell Get-Date

Working with Date Variables in PowerShell

In PowerShell, you can assign dates and times to variables and use them in various operations. To assign a date and time to a variable, you can use the PowerShell Get-Date cmdlets, as shown below:

$date = Get-Date "2022-01-01"

Once you have assigned the date and time to a variable, you can use other PowerShell cmdlets to manipulate it. For instance, you can use the AddDays method to add or subtract days from the date. You can also extract the individual components, such as day, month, year, etc., using the properties of the DateTime object. For example, to retrieve the current year:

(Get-Date).Year
#Output: 2021

#More Examples
(Get-Date).DayOfWeek
#Output: Saturday

(Get-Date).DayOfWeek.value__
#Output: 6

PowerShell Get-Date also offers a wide range of methods and properties for working with date and time objects. These allow you to extract specific components, such as the day, month, year, hour, minute, or second, and perform various operations. PowerShell Get-Date also offers a wide range of methods and properties for working with date and time objects. Here are some examples:

  • $date.DayOfWeek returns the day of the week.
  • $date.DayOfYear returns the day of the Year.
  • $date.Month returns the month.
  • $date.Year returns the year.
  • $date.Hour returns the hour.
  • $date.Minute returns the minute.
  • $date.Second returns the second.

By utilizing these properties, you can perform advanced calculations, manipulate specific components, or extract information as needed. Apart from properties there are methods in the DateTime object, such as “IsDaylightSavingTime()” to check if daylight savings time is ON.

Formatting Date and Time in PowerShell

PowerShell provides several ways to format dates and times. You can use the -Format parameter with the Get-Date cmdlet to format the output date and time. The parameter accepts various standard and custom format strings. E.g., the below script gets you the simple date format:

Get-Date -Format "d"

You can supply the format string to get the date in specific format “dd-MMM-yyyy”:

Get-Date -Format "dd-MMM-yyyy" #Output: 21-Aug-2021

 Get-Date -Format "MM/dd/yyyy HH:mm K"  # Output: 08/21/2023 20:17 +04:00 (with Time zone offset)

For instance, if you want to display the time in a short format, you can use the following command:

Get-Date -Format "t"

To display the 12-hour format, use the following:

Get-Date -Format "hh:mm:ss tt"

#For 24-Hour format, use: Get-Date -Format "HH:mm:ss"

For more information on formatting date in PowerShell, refer: How to Format Date in PowerShell?

Getting the date without the time using PowerShell Get-Date

In certain scenarios, you may only require the date without the time component. Get-Date allows you to extract the date portion by using the ToString() method with a specified format. For example:

(Get-Date).ToString("dd/MM/yyyy")
#Output: 21/08/2023

(Get-Date).ToString("dddd,dd MMM yyyy")
#Output: Monday,21 Aug 2023

This will return the current date in the format dd/MM/yyyy, without the time component. You can customize the format string according to your preference. You can also use the Get-Date command to retrieve the date and time in different formats. Here is one more example:

Get-Date -Format "MM-dd-yyyy"

#Output: 08-21-2021

This will output the Month number and Day of the month in 2 digits, and the year in a 4-digit format. Alternatively, you can use the parameter -UFormat to specify a custom date and time in UNIX format. The parameter accepts the same format strings as the Microsoft .NET Framework.

Get-Date -UFormat "%Y-%m-%d"

#Output (ISO Format): 2021-08-21

Another way to get the date part from Get-Date cmdlet is using its -DisplayHint parameter.

Get-Date -DisplayHint Date

Use the (Get-Culture).DateTimeFormat cmdlet to get all date time formats of the local computer’s culture settings:

PS C:\> (Get-Culture).DateTimeFormat
                                                                                                                                                                                AMDesignator                     : AM
Calendar                         : System.Globalization.GregorianCalendar
DateSeparator                    : /
FirstDayOfWeek                   : Sunday
CalendarWeekRule                 : FirstDay
FullDateTimePattern              : dddd, MMMM d, yyyy h:mm:ss tt
LongDatePattern                  : dddd, MMMM d, yyyy
LongTimePattern                  : h:mm:ss tt
MonthDayPattern                  : MMMM d
PMDesignator                     : PM
RFC1123Pattern                   : ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
ShortDatePattern                 : M/d/yyyy
ShortTimePattern                 : h:mm tt
SortableDateTimePattern          : yyyy'-'MM'-'dd'T'HH':'mm':'ss
TimeSeparator                    : :
UniversalSortableDateTimePattern : yyyy'-'MM'-'dd HH':'mm':'ss'Z'
YearMonthPattern                 : MMMM yyyy
AbbreviatedDayNames              : {Sun, Mon, Tue, Wed...}
ShortestDayNames                 : {Su, Mo, Tu, We...}
DayNames                         : {Sunday, Monday, Tuesday, Wednesday...}
AbbreviatedMonthNames            : {Jan, Feb, Mar, Apr...}
MonthNames                       : {January, February, March, April...}
IsReadOnly                       : False
NativeCalendarName               : Gregorian Calendar
AbbreviatedMonthGenitiveNames    : {Jan, Feb, Mar, Apr...}
MonthGenitiveNames               : {January, February, March, April...}

Calculating the difference between two dates in PowerShell

At times, you may need to calculate the duration or difference between two dates. PowerShell offers the Subtract() method of the DateTime object to achieve this. For example, to calculate the number of days between two dates:

$startDate = Get-Date -Year 2021 -Month 1 -Day 1
$endDate = Get-Date -Year 2021 -Month 12 -Day 31
$duration = $endDate.Subtract($startDate).Days

Here, $startDate and $endDate represent the two dates between which you want to calculate the difference. The result will be stored in the variable $duration. Instead of “Subtract”, you can use:

$dateStart = Get-Date -Date "2023-01-01"
$dateEnd = Get-Date
$diff = $dateEnd - $dateStart #Alternatively: New-TimeSpan -Start $datestart -End $dateEnd
$diff.Days

PowerShell Get-Date allows you to easily calculate the difference between two dates using the Subtract() method. This method returns a TimeSpan object representing the time difference between two dates. Here’s an example:

$date1 = Get-Date "2021-01-01"
$date2 = Get-Date "2022-01-01"
$diff = $date2.Subtract($date1)
$diff

In this example, we create two variables, $date1 and $date2, and assign them specific dates. We then use the Subtract() method to calculate the difference between $date2 and $date1. The result is a TimeSpan object that represents the duration between the two dates. You can access the Days, Hours, Minutes, Seconds, and other properties of the TimeSpan object to retrieve specific information about the time difference.

difference between two dates

Getting the current time with PowerShell

In addition to retrieving the current date and time, PowerShell also allows you to extract only the time component. This can be useful in scenarios where you need to perform time-specific operations. To get the current time using Get-Date, you can use the TimeOfDay property:

(Get-Date).TimeOfDay
Get Time of the day

To get just the current time element, you can also use:

 Get-Date -Format "hh:mm:ss tt"

This will return the current time in the format HH:mm:ss AM/PM.

Comparing Dates in PowerShell

PowerShell provides several operators and cmdlets for comparing dates and times. You can use the -lt, -le, -eq, -ne, -gt, and -ge operators to compare dates and times.

For instance, to check if a date is greater than another date, you can use the following command:

$date1 = Get-Date "2022-01-01"
$date2 = Get-Date "2022-01-02"
if ($date1 -lt $date2) {
    "First date is earlier!"
}

PowerShell Get-Date allows you to compare dates easily, enabling you to perform various operations based on date comparisons. The CompareTo() method is particularly useful for this purpose. It returns an integer value indicating the relationship between two dates. Here’s an example:

$date1 = Get-Date "2021-01-01"
$date2 = Get-Date "2022-01-01"

$result = $date1.CompareTo($date2)

In this example, we create two variables, $date1 and $date2, and assign them specific dates. We then use the CompareTo() method to compare $date1 and $date2. The result will be an integer value:

  • -1 if $date1 is earlier than $date
  • 0 if they are equal
  • 1 if $date1 is later than $date2.

You can use this information to conditionally execute code based on date comparisons.

To check if a given date is in the past:

$GivenDate -lt (Get-Date)

Here, $givenDate represents the date you want to compare with the current date. You can modify the comparison operator based on your specific needs.

Get-Date with Calculations

PowerShell provides several cmdlets and methods for performing advanced date and time manipulation. Some of these operations include Adding Date, Subtracting Date, and finding the TimeSpan, among others. Here are some examples:

 (Get-Date).AddDays(30)

This will display the date and time that is 30 days from now! Similarly, you can add hours to the current time as:

 (Get-Date).AddHours(2).ToString("MM-dd-yyyy HH:mm:ss")

This will display the date and time 2 hours from now in the format of month-day-year hour:minute:second. Similar to AddDays(), We have methods available for adding Months, Years, Hours, Minutes, etc.:

(get-date).AddDays(5)
(get-date).AddMonths(5)
(get-date).AddYears(5)
(get-date).AddHours(5)
(get-date).AddMinutes(5)
(get-date).AddSeconds(5)

Time Comparison: Let’s say a task was logged with a 48-hour resolution SLA and you want to calculate time:

$logDate = "2023-08-18 14:00"
$dueDate = ([datetime]$logDate).AddHours(48)
if ((Get-Date) -gt $dueDate) {
    "SLA breached!"
}

Retrieving yesterday’s date with PowerShell

Sometimes, you may need to retrieve yesterday’s date for various purposes. PowerShell provides a simple method to achieve this using the AddDays() method. To retrieve yesterday’s date, you can subtract one day from the current date:

(Get-Date).AddDays(-1)

This will return the date corresponding to yesterday. Similarly, you can get last month using:

$LastMonth = (Get-Date).AddMonths(-1).ToString('MMMM')

Adding or subtracting days from a date in PowerShell

For instance, to add 10 days to a date, you can use the Add-Date cmdlet as shown below:

$date = Get-Date "2022-01-01"
$date = $date.AddDays(10)

In many scenarios, you may need to add or subtract a certain number of days from a given date. PowerShell provides a simple way to accomplish this using the AddDays() and Subtract() methods of the DateTime object. For example, to add 7 days to the current date:

(Get-Date).AddDays(7)

Similarly, to subtract 7 days from the current date, use:

(Get-Date).AddDays(-7)

As an alternative option, you use the “Subtract()” method of the DateTime object as:

(Get-Date).Subtract([TimeSpan]::FromDays(3))

You can adjust the number of days as per your requirements. Or even minutes: Let’s say 15 min from now!

$FutureTime = (Get-Date).AddMinutes(15)

Find out the Total execution time of a PowerShell Script

Although you can use Measure-Command, and Stopwatch methods to find the script execution time, Here is a simple way to measure the time taken to complete the execution of a PowerShell script:

# Capture the start time
$startTime = Get-Date

# Do some processing
Start-Sleep -Seconds 5

# Capture the end time
$endTime = Get-Date

# Calculate the time difference using New-TimeSpan
$executionDuration = New-TimeSpan -Start $startTime -End $endTime

# Display the execution time
Write-Output "Script took $($executionDuration.TotalMilliseconds) milliseconds to execute."
Write-Output "Script took $($executionDuration.TotalSeconds) seconds to execute."

Converting Get-Date to string format in PowerShell

Sometimes, you may need to convert the Get-Date output to a string format for further processing or displaying purposes. PowerShell provides several options for converting Get-Date to a string. One of the commonly used methods is the ToString() method, which allows you to specify the desired format.

(Get-Date).ToString("yyyy-MM-dd HH:mm:ss")

This will convert the current date and time to a string format in the format yyyy-MM-dd HH:mm:ss. You can customize the format specifier to match your requirements, such as displaying the time, including milliseconds, or using different separators.

Get-Date -Format "dd-MM-yyyy"

This converts the date to a specific string format. E.g., 20-08-2021.

How to Convert String to Date in PowerShell?

How about the reverse? If you have a string object representation of a date, and you want to convert it to a DateTime object, Here is how you can use the Get-Date cmdlet:

$dateString = "2021-08-21"
$dateObject = Get-Date -Date $dateString
$dateObject

However, if the date string is in a format that’s not immediately recognized by Get-Date, you might need to use the [datetime]::ParseExact() method to specify the format explicitly.

[datetime]::ParseExact("20-08-2021", "dd-MM-yyyy", $null)

This takes the string and converts it into a datetime object.

Adding the date to a filename using PowerShell

When working with files, it is often useful to append the current date to the filename for better organization. PowerShell makes this task easy using Get-Date. You can use the ToString() method to format the date and then concatenate it with the filename string.

For example: When troubleshooting systems, log files are often generated. To prevent overwriting and to ensure easy retrieval, you can append the date and time to the filename.

$Filename = "log_" + (Get-Date).ToString("yyyyMMdd_HHmmss") + ".log"

This will create a filename in the format log_yyyyMMdd_HHmmss.log, E.g., “log_20210821_082843.log”. You can adjust the format string as needed.

Here is another way to timestamp filenames:

$LogFile = "C:\Logs\MyLog_$(Get-Date -Format "yyyyMMdd_HHmmss").log"

The command will create a log file with a filename in the format MyLog_20220101_120000.log.

Create a Directory with Year-Month-Day Timestamp:

If you want to create a directory with a timestamp appended to its name, PowerShell is your reliable ally. Here is an example:

#Frame Folder Name with Timestamp
$BackupFolderName = "Backup_" + (Get-Date -Format "yyyy-MM-dd")

#Create a New Folder
New-Item -Path "C:\Backup" -Name $BackupFolderName -ItemType Directory

This creates a folder “Backup_2021-08-21” to the “C:\Backup”.

Practical Examples of Using PowerShell Get-Date

Let’s look at some practical examples of using PowerShell Get-Date.

Example 1: Password Expiration Reminder Date

In many enterprise setups, user passwords expire after a set period. With Get-Date, you can calculate and remind users when they need to change their passwords.

$expiryDate = (Get-Date).AddDays(90)
"Your password will expire on $expiryDate."

The command will create a log file with a filename in the format MyLog_20220101_120000.log.

Example 2: Scheduling a Task Time

Suppose you want to schedule a task to run at a specific date and time. You can use the following command:

$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date "2022-01-01 10:00:00")

The command will create a trigger that will run the task once at 10:00:00 on January 1st, 2022.

Example 3: Age Calculation

If you need to calculate someone’s age based on their birthdate:

$birthDate = "1990-08-20"
$age = ((Get-Date) - [datetime]$birthDate).Days / 365
[math]::Floor($age)

Example 4: Cleaning up Old Logs

Let’s say you want to delete log files older than 30 days:

$CutOffDate = (Get-Date).AddDays(-30)
Get-ChildItem -Path "C:\Logs" | Where-Object { $_.CreationTime -lt $CutOffDate } | Remove-Item

Example 5: Validating Date Input

If you’re taking a date input from a user and need to check if it’s within the last 30 days:

$userInput = "2021-07-20"
$inputDate = [datetime]$userInput
$currentDate = Get-Date
If (($currentDate - $inputDate).Days -le 30) {
    "The date is within the last 30 days."
}

Using the PowerShell Now function

PowerShell offers the Now function, which combines date and time components into a single object. This can be useful for time management tasks that require precise timing. To retrieve the current date and time using “Now”, you simply need to call the function:

[DateTime]::Now
#Output: Monday, August 21, 2023 10:46:02 PM

The output will be in the default format specified by the system’s regional settings.

Best Practices for Using PowerShell Get-Date

To get the best out of PowerShell Get-Date, it’s essential to follow some best practices. Adopting these practices ensures the reliability, readability, and maintainability of your scripts.

  • Use Standard DateTime Formats: When formatting dates and times, it’s best to use standard DateTime formats. These formats are recognized across different platforms and applications, making it easier to share and manipulate data.
  • Use Variables to Store Dates and Times: To make your code more readable and maintainable, it’s best to use variables to store dates and times. This makes it easier to reference the date and time in your code and modify it when necessary.
  • Validate Date Inputs: If your script or function accepts date inputs, always validate them to ensure they are in the correct format. This avoids potential errors or incorrect calculations.
  • Always Handle Time Zones: Consider the Kind property of a [datetime] object (e.g., Local, Utc, Unspecified). If you’re working with date and times from multiple time zones or saving dates for later use, consider converting to UTC time (Universal time coordinate) : (Get-Date).ToUniversalTime()
  • Use [datetime] Type Accelerator for Conversion: When converting strings to date, use the [datetime] type accelerator for clarity and consistency. $date = [datetime]”2021-08-20″
  • Be Mindful of Culture-Specific Settings: Remember that date formats can be culture-specific. Ensure that your scripts can handle different formats, especially if they will be used in different locales.
  • Opt for .NET Methods When Needed: Sometimes, more specific operations on dates (like checking if a year is a leap year) are easier using .NET methods. Don’t shy away from them. E.g., [DateTime]::IsLeapYear((Get-Date).Year)
  • Consistent Naming in Scripts: When using Get-Date in scripts, maintain a consistent naming convention for date variables to enhance readability. E.g., “StartDate”, “EndDate”.

Wrapping up

In conclusion, mastering PowerShell Get-Date is an essential skill for any PowerShell user. By using parameters and calculations, users can retrieve and manipulate date and time information in various formats. Whether you are a system administrator or an IT professional, Get-Date is a command that you should have in your toolbelt. Whether you need to retrieve the current date and time, manipulate dates, compare dates, or perform complex date calculations, PowerShell Get-Date provides the tools and flexibility to meet your needs.

With the knowledge and skills outlined in this guide, you can confidently use the Get-Date cmdlet to perform various date and time operations in PowerShell. By understanding the basics of PowerShell Get-Date and exploring its various features and functionalities, you can significantly enhance your scripting skills.

How do I convert a date to a string in PowerShell?

To convert a date to a string in PowerShell, you can use the ToString() method with a specific format. For example, you can use the following code:
(Get-Date).ToString("MM/dd/yyyy")
(Get-Date "2021-08-21").ToString("dd-MM-yyyy")

How to get only the date from DateTime in PowerShell?

To get only the date from a DateTime object in PowerShell, you can use the ToString() method with a specific date format. Here’s how you can do it:
(Get-Date).ToString("yyyy-MM-dd")

How to get the Date format month name in PowerShell?

Use the ToString() method with a custom format string to get the month name. Here’s an example: (Get-Date).ToString("MMMM")

How do I get the month in PowerShell?

To get just the month, you can use the Month property of the returned DateTime object. Here are the examples:
(Get-Date).Month
(Get-Date).ToString("MMMM")

How do I get the current month and year in PowerShell?

To get the current month and year in PowerShell, you can use the Get-Date cmdlet in the below ways:
(Get-Date).ToString("yyyy-MM")
Get-Date -Format "MMMM-yyyy"

What is the PowerShell operator for date comparison?

How do I add 7 days to a Date in PowerShell?

To add 7 days to a date in PowerShell, you can use the AddDays() method. Here are two ways to do it:
(Get-Date).AddDays(7)
(Get-Date "2021-01-01").AddDays(7)

How to get the year from Date in PowerShell?

To get the year from a date in PowerShell, you can use the Year property of the DateTime object. E.g., (Get-Date).Year .You can use the ToString() method with a custom format string. For example: (Get-Date).ToString("yyyy")

How to get AM and PM in Date format PowerShell?

To get the “AM” or “PM” indicator in the date format in PowerShell, you can use the “tt” format specifier with the ToString() method of the DateTime object. Here’s an example:
(Get-Date).ToString("yyyy-MM-dd tt")

How do I get the current time stamp in PowerShell?

To get the current time stamp in PowerShell, you can use the Get-Date cmdlet. Simply type “Get-Date” in the PowerShell console and press enter. This will display the current date and time in the default format. If you want to customize the format, use the -Format parameter followed by a format string. For example, “Get-Date -Format ‘yyyy-MM-dd HH:mm:ss'” will give you the current time stamp in the format “YYYY-MM-DD HH:MM:SS”.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

One thought on “PowerShell Get-Date: Everything You Need to Know!

  • Your PowerShell articles are very helpful to me. They are clear and easy to understand. Thank you for sharing your knowledge.
    How can the time be stripped from your cleanup example so that any aged file with that date will be considered – regardless hour, minute, second?
    Let’s say you want to delete log files older than 30 days:
    $CutOffDate = (Get-Date).AddDays(-30)

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *