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:

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:

  • 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 (24-hour format, hh would have been 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 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 effect is documented on MSDN:

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 date can be extracted using what is known as a reference. That is, a variable with the same type ([DateTime]) is provided as a reference; the method fills in the value of the variable via the reference:

$date = Get-Date    # A valid DateTime object 
$string = '20170102-2030'   
if ([DateTime]::TryParseExact($string,  
                              'yyyyddMM-HHmm', 
                              (Get-Culture), 
                              'None', 
                              [Ref]$date)) { 
    $date 
} 

The highlighted line shows the reference to the date variable. The date held in this variable will be changed if TryParseExact succeeds.

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

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