Как получить дату без времени в power shell

PowerShell Get-Date

Ever found yourself in the middle of a scripting task when you suddenly need to add a timestamp? That’s happened to me more times than I can remember! When that occurs, I always rely on my good friend: PowerShell’s Get-Date command. Get-Date is like a dependable sidekick, ready to help you quickly get the current date and time or do calculations whenever you need it.

In this guide, let’s team up to uncover the cool things Get-Date can do in PowerShell. I’ll begin by walking you through the essentials of retrieving dates and times. After that, we’ll tackle some more advanced techniques, such as formatting and calculations.

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.

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:

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:

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)

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

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

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 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.

$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:

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 the 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:

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:

:/>  Surface Pro

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

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
[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

$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

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

The command will create a trigger to 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

$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

  • 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”.
:/>  Как изменить изображение рабочего стола в Windows 10 без активации и как установить или изменить обои на рабочем столе Windows 7?

Wrapping up

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?

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?


The easiest way to format a datetime in PowerShell is to use the ToString() method.

Here is the basic syntax you can use:

 = Get-Date

.ToString("")

This particular example uses Get-Date to save the current date and time in a variable named $mydate, then uses ToString() to format the date using a MM/dd/yyyy format.

  • dd: 2 digit day of the month
  • MM: 2 digit month number
  • YY: 2 digit year number
  • dddd: Full name of day
  • MMMM: Full name of month
  • yyyy: 4 digit year number
  • HH:mm: Time in 24-hour format
  • HH:mm:ss: Time in 24-hour format with seconds
  • HH:mm:ss.fff: Time in 24-hour format with milliseconds
  • hh:mm: Time in 12-hour format
  • hh:mm tt: Time in 12-hour format with AM/PM

Example 1: Format DateTime Using MM/dd/yyyy

 = Get-Date

.ToString("")

Format DateTime in PowerShell

Notice that the datetime is formatted as 03/01/2024.

Example 2: Format DateTime Using MM/dd/yyyy HH:mm:ss

 = Get-Date

.ToString("")

Как получить дату без времени в power shell

Notice that the datetime is formatted as 03/01/2024 08:38:10.

Example 3: Format DateTime Using MM/dd/yyyy hh:mm tt

 = Get-Date

.ToString("MM/dd/yyyy hh:mm tt")

PowerShell format datetime with AM / PM

Notice that the datetime is formatted as 03/01/2024 08:40 AM.

By using the tt specifier, we are able to add the AM / PM distinction at the end of the datetime.

Note: In this tutorial we only illustrated a few examples of how to format datetimes in PowerShell. Feel free to use any combination of specifiers you would like to format your datetime in the exact way you want.

PowerShell: How to Compare Dates
PowerShell: How to List Files in Directory by Date
PowerShell: Get List of Files Modified After Certain Date
PowerShell: Check if File Has Been Modified in last 24 Hours

Оставьте комментарий