EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial PowerShell Convert String to Date
Secondary Sidebar
PowerShell Tutorial
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Interview Questions
    • PowerShell Interview Questions

Related Courses

Shell Scripting Course

All in One Data Science Courses

Data Visualization Courses

PowerShell Convert String to Date

By Priya PedamkarPriya Pedamkar

POWERSHELL CONVERT STRING TO DATE

Introduction to PowerShell Convert String to Date

In many cases, it may be required to convert a string to a date variable or a date-time object. In PowerShell, this can be done in many ways. Some of the ways in which this can be done by using type casting, getting the date in US format, using parsing of Date Time. This conversion is required for many purposes like sending a string object to DB table, so a conversion is required when the input from the user is received in a string format and then needs to be formatted for further process. This article will cover in detail the various ways in which a string object can be converted to a date-time object.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Below is the syntax of the Datetime Parse:

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,112 ratings)

[Datetime]::ParseExact('07/15/2019', 'MM/dd/yyyy', $null)

Where the first parameter is the string that needs to be converted, the second parameter is the format of the date to be produced and the third is a null character.

Code:

Write-Host "Welcome to string to date conversion example"
$string='11/11/2019'
Write-Host "The variable type now is" $string.GetType()
$string=[Datetime]::ParseExact($string, 'MM/dd/yyyy', $null)
Write-Host "After conversion the type is" $string.GetType() "and the value is" $string

Output:

PowerShell Convert String to Date 1

Types of Date Format Available in PowerShell

Before learning about the various ways in which string can be converted to a data object, it is important to learn about various date types that are available in PowerShell. It will be helpful during conversion.

The following are the various date formats available in PowerShell.

d: Denotes ShortDate

D: Denotes LongDate

f: Denotes long date, short time

F: Denotes long date, long time

t: Denotes Short time format

T: Denotes Long time format

m, M: Month Day format

g: Denotes general data time short format

G: Denotes general data time long format

Y or y: Denotes Year month pattern

Examples of PowerShell Convert String to Date

Below are the examples of PowerShell:

Example #1

Code:

Write-Host "Date in long date format" -ForegroundColor DarkYellow
Get-Date -Format D
Write-Host "long date short time" -ForegroundColor DarkYellow
Get-Date -Format f
Write-Host "long date long time" -ForegroundColor DarkYellow
Get-Date -Format F
Write-Host "Date in general date time short format" -ForegroundColor DarkYellow
Get-Date -Format g
Write-Host "Date in general date time long format" -ForegroundColor DarkYellow
Get-Date -Format G
Write-Host "month day format" -ForegroundColor DarkYellow
Get-Date -Format m
Write-Host "Date in year format" -ForegroundColor DarkYellow
Get-Date -Format y

Output:

PowerShell Convert String to Date 1

Example #2

Code:

Write-Host "String to Date conversion examples"
Write-Host "example of yymmddhhmm format"
[System.DateTime]::ParseExact('1605221412','yyMMddHHmm',$null)
Write-Host "Global time example"
[System.DateTime]::ParseExact('1805221412','yyMMddHHmm',[System.Globalization.DateTimeFormatInfo]::CurrentInfo)
Write-Host "US Timings example"
[System.DateTime]::ParseExact('1804221610','yyMMddHHmm',[System.Globalization.CultureInfo]::GetCultureInfo('en-US'))
Write-Host "Complex example of custome pattern"
[string]$test = 'year 2020 and date 12 and month feb and time 9 00'
[string]$testpattern = '\year yyyy an\d \da\te dd an\d \mon\t\h MMM an\d \ti\me H mm'
[DateTime]::ParseExact($test, $testpattern, $null)
Write-Host "mmddyy format example"
[System.DateTime]::ParseExact('111199','mmddyy',$null)
Write-Host "mmddyyyy format example"
[System.DateTime]::ParseExact('11111999','mmddyyyy',$null)

Output:

Conversion Example 2

Example #3

Code:

Write-Host "Demo about coverting strings into dates and finding difference" -ForegroundColor DarkYellow
$stringa="01/01/2020"
$stringb="01/01/1990"
Write-Host "The current data type of the objects is" $stringa.GetType() "and" $stringb.GetType() -ForegroundColor DarkYellow
Write-Host "Converting the first string to date" -ForegroundColor DarkYellow
$date1=[System.DateTime]::ParseExact($stringa,'mm/dd/yyyy',$null)
Write-Host "the value of a the first date after conversion is "$date1 "and the type is" $date1.GetType() -ForegroundColor DarkYellow
Write-Host "Converting the second string to date" -ForegroundColor DarkYellow
$date2=[System.DateTime]::ParseExact($stringb,'mm/dd/yyyy',$null)
Write-Host "the value of a the first date after conversion is "$date2"and the type is" $date2.GetType() -ForegroundColor DarkYellow
$difference= $date2- $dateB
Write-Host "number of days difference between the two dates is " $difference.Days -ForegroundColor DarkYellow
Write-Host "number of hours difference between the two dates is " $difference.Hours -ForegroundColor DarkYellow
Write-Host "number of minutes difference between the two dates is " $difference.Minutes -ForegroundColor DarkYellow
Write-Host "number of seconds difference between the two dates is " $difference.Seconds -ForegroundColor DarkYellow
Write-Host "number of milliseconds difference between the two dates is " $difference.Milliseconds -ForegroundColor DarkYellow
Write-Host "number of total days difference between the two dates is " $difference.TotalDays -ForegroundColor DarkYellow
Write-Host "number of total hours difference between the two dates is " $difference.TotalHours -ForegroundColor DarkYellow
Write-Host "number of total minutes difference between the two dates is " $difference.TotalMinutes -ForegroundColor DarkYellow
Write-Host "number of total seconds difference between the two dates is " $difference.TotalSeconds -ForegroundColor DarkYellow
Write-Host "number of total milliseconds difference between the two dates is " $difference.TotalMilliseconds -ForegroundColor DarkYellow

Output:

PowerShell Convert Srring example 3

Important thing to be considered while working with date

It is important to know the system’s local setting before typecasting a string into a date. If the system follows the UK date format and if we specify US time format, then it is possible that either an error may be generated, or the wrong day is displayed. For e.g., 7/16/2020 denotes July 16 in us format, whereas in the UK it generates an error as the second is considered as a month and month cannot be greater than 12. To overcome this, local cultural settings can be used.

Example #4

Code:

Write-Host "Local settings demo"
$string="13/2/2020"
$date= [DateTime] $string

Output:

Local settings Demo Example 4

In the above output, an error is thrown as the system follows as the US time zone and month come first, so it can’t be greater than 12. If we change the 13 to 12 then the following output is produced.

Code:

Write-Host "Local settings demo"
$string="12/2/2020"
$date= [DateTime] $string
Write-Host $date -ForegroundColor DarkYellow

Output:

Local Cultural Setting Example 6

Example #5

Code:

$tdate="06/16/2016 3:14:03 PM"
$CTDC = (Get-Culture).DateTimeFormat
Write-Host "Systems culture data time format is" $CTDC -ForegroundColor DarkYellow
$ctdcDateFormat = $CTDC.ShortDatePattern
Write-Host "systems short date pattern is" $ctdcDateFormat -ForegroundColor DarkYellow
$ctdcTimeFormat = $CTDC.LongTimePattern
Write-Host "systems long time pattern is" $ctdcTimeFormat -ForegroundColor DarkYellow
$DateTimeFormat = "$ctdcDateFormat $ctdcTimeFormat"
$DateTime = [DateTime]::ParseExact($tdate,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)

Output:

PowerShell Convert String to Date 5

Conclusion

Thus, the article covered in detail about the conversion from a string object to a date-time object. It explained in detail the various ways of converting a string to a date-time object, how a string object can be converted to a specific date-time format. It also explained in detail the error that may be encountered during conversion and how to overcome them. It is also wise to learn about the current system’s format before conversion. To learn more in detail it is advisable to write sample programs and practice them.

Recommended Articles

This is a guide to PowerShell Convert String to Date. Here we discuss a brief overview on PowerShell Convert String to Date and its different types along with examples. You can also go through our other suggested articles to learn more –

  1. How PowerShell While Loop Works?
  2. What is PowerShell Break Statement?
  3. Introduction to PowerShell Get-Date
  4. PowerShell Get-Location (Examples)
  5. PowerShell Convert to String | Parameters
Popular Course in this category
PowerShell Training (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |   4+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
Data Visualization Training (15 Courses, 5+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more