Parsing dates

The Get-Date command is the best first stop for converting strings into dates. Get-Date deals with a reasonable number of formats.

If, however, Get-Date is unable to help, the DateTime class has two static methods that may be used:

  • ParseExact
  • TryParseExact

The format strings used by these methods are documented on MSDN, available at https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx.

The ParseExact method accepts one or more format strings, and returns a DateTime object:

$string = '20170102-2030'  # Represents 1st February 2017, 20:30 
[DateTime]::ParseExact($string, 'yyyyddMM-HHmm', (Get-Culture)) 

The culture, returned from Get-Culture, used previously, fills in the format provider argument.

The format string uses the following syntax:

  • yyyy to represent a four-digit year
  • dd for a two-digit day
  • MM for a two-digit month
  • HH for the hours in the day (this is for 24 hour format; hh is used for 12 hour format)

This can be extended to account for more than one date format. In this case, two variations of the format are accepted, the second of which expects seconds (ss):

$strings = '20170102-2030', '20170103-0931.24' 
[String[]]$formats = 'yyyyddMM-HHmm', 'yyyyddMM-HHmm.ss' 
foreach ($string in $strings) { 
    [DateTime]::ParseExact( 
        $string,  
        $formats, 
        (Get-Culture), 
        'None' 
    ) 
} 

The final argument, None, grants greater control over the parsing process. The other possible values and the effects are documented on MSDN, available at https://msdn.microsoft.com/en-us/library/91hfhz89(v=vs.110).aspx.

The TryParseExact method has a safer failure control than ParseExact, which will throw an exception if it fails. The TryParseExact method itself returns true or false, depending on whether or not it was able to parse the string.

The parsed date can be extracted using a reference to an existing date. This is an existing variable that holds DateTime. The method updates the value held in the variable, if parsing is successful, as follows:

$date = Get-Date 01/01/1601   # A valid DateTime object with an obvious date
$string = '20170102-2030'
if ([DateTime]::TryParseExact($string, 'yyyyddMM-HHmm', $null, 'None', [Ref]$date)) {
$date
}

The updated value of the $date variable is shown when the TryParseExact method returns true, and the body of the if statement executes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.202.224