Solved

Isolate Date in string

Posted on 2013-05-24
10
415 Views
Last Modified: 2013-05-28
I am trying to isolate the date in a string, the string is non-standard and can be be an number or character before and after the date but the date is in a semi-standard format similar to 1/9/2012 or 01/09/2012.

I will need to isolate it so I can compare the date to the current date and take an action.

Example string: ABC;12345;IU:TYU; Disabled 05/25/2012 CB00757

Thank you
0
Comment
Question by:patrickm12981
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 29

Expert Comment

by:Randy Downs
ID: 39196042
Maybe this will help. Their example is looking for dates in the format 05/22/2012

http://stackoverflow.com/questions/10710950/powershell-extract-timestamp-from-string


... parse out the date/time string with a regular expression and then convert it to a date/time object:

$line = 'C:\Documents and Settings\admin\Local Settings\Application Data\Microsoft\SyncToy\2.0\SyncToyLog.log:325:SYNC: 05/22/2012 14:54:55:857: SyncToy run of Profile Backup (C:\Documents and Settings\admin\, H:\Sync\) completed at 5:22/2012 2:54:55 PM.'

$dateTimeString = [regex]::Matches($line, '(\d\d/\d\d/\d\d\d\d.+): ')[0].Groups[1].Value

Then convert it to a datetime object:

$provider = New-Object System.Globalization.CultureInfo "en-US"

$dateTime = [datetime]::ParseExact($dateTimeString, 'MM/dd/yyyy HH:mm:ss:fff', $provider)

Now you can display it or store it in a variable however you want:

$dateTime -f 'MM/dd/yyyy HH:mm:ss'

0
 

Author Comment

by:patrickm12981
ID: 39196092
I tried that example, it didn't work for me.
0
 
LVL 29

Expert Comment

by:Randy Downs
ID: 39196097
Does it find any of the dates?
0
 

Author Comment

by:patrickm12981
ID: 39196105
No.

$line = "ABC;12345;IU:TYU; Disabled 05/25/2012 CB00757"
$dateTimeString = [regex]::Matches($line, '(\d\d/\d\d/\d\d\d\d.+): ')[0].Groups[1].Value
$provider = New-Object System.Globalization.CultureInfo "en-US"
$dateTime = [datetime]::ParseExact($dateTimeString, 'MM/dd/yyyy HH:mm:ss:fff', $provider)
$dateTime -f 'MM/dd/yyyy HH:mm:ss'
Write-Host  $dateTime.

Open in new window


Cannot index into a null array.
At E:\Scripts\User_Delete\test.ps1:2 char:81
+ $dateTimeString = [regex]::Matches($line, '(\d\d/\d\d/\d\d\d\d.+): ')[0].Groups[ <<<< 1].Value
    + CategoryInfo          : InvalidOperation: (1:Int32) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At E:\Scripts\User_Delete\test.ps1:4 char:35
+ $dateTime = [datetime]::ParseExact <<<< ($dateTimeString, 'MM/dd/yyyy HH:mm:ss:fff', $provider)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Open in new window

0
 
LVL 29

Expert Comment

by:Randy Downs
ID: 39196128
Try single quotes

$line = 'ABC;12345;IU:TYU; Disabled 05/25/2012 CB00757'
0
 

Author Comment

by:patrickm12981
ID: 39196182
No Change.
0
 
LVL 83

Expert Comment

by:oBdA
ID: 39196441
Try
$StringRaw = "ABC;12345;IU:TYU; Disabled 05/25/2012 CB00757"
If ($StringRaw -match '\d\d/\d\d/\d\d\d\d') {
	$StringDateTime = [datetime]::ParseExact($Matches[0], 'MM/dd/yyyy', [System.Globalization.CultureInfo]::GetCultureInfo("en-US"))
	Write-Output "Date identified from string `'$StringRaw`': $StringDateTime"
} Else {
	Write-Error "Could not identify a date in string `'$StringRaw`'."
}

Open in new window

0
 
LVL 39

Accepted Solution

by:
footech earned 500 total points
ID: 39197261
More of an aside, but the syntax in the last line of the example from StackOverflow is wrong.
       $dateTime -f 'MM/dd/yyyy HH:mm:ss'
$dateTime -f '' (those are two single quotes) or any variation of items to the right of "-f" would give the same result.  It should be
'{0:MM/dd/yyyy HH:mm:ss}' -f $dateTime

Anyway, the first example given would only match a date in the form of "xx/xx/xxxx jkslajfksa;ejf3:sadfsds:sadfsdf;  : " (where x is any single digit).  The colon-space at the end is important.  Unfortunately that nonsense string I just typed would match.  The regex pattern was constructed to try to also match hours, minutes, and seconds from the line in the example.

The second example (from oBdA) narrows down the regex pattern to only look for a date, but it's still looking for the pattern "xx/xx/xxxx".

Since you mentioned that the date may vary in its format, we'd need to know what all the possible variations are.  Hopefully the example string you posted is representative of the fact that there are no similar portions of the string with the same format as the date.
Here's a regex pattern that should match given the variability that you've mentioned so far.
"\s(\d{1,2}/\d{1,2}/\d{4})\s"
You could even construct a regex pattern that would limit the matches further to only valid numbers for months, days, and a range of years, but that's probably overkill.
$line = "ABC;12345;IU:TYU; Disabled 5/5/2012 CB00757"
If ($line -match "\s(\d{1,2}/\d{1,2}/\d{4})\s")
{
    $dateTimeString =  Get-Date($matches[1])
    If ($dateTimeString -lt (Get-Date))  #example of a condition check
    { write-output "I'm gonna do something!" }
}

Open in new window

0
 
LVL 39

Expert Comment

by:footech
ID: 39197329
BTW, I was messing around and came up with a regex pattern to do some validation of the date (what else am I supposed to do on a Saturday night?).  It handles the number of days correctly for each month, with the slight exception of February, where it always allows up to 29 days regardless of whether it's a leap year or not, and it allows years in the range 1900-2099 (didn't bother to account for the possibility of two-digit years).  It works for both single digit days and months or zero-padded.
"\b((((0?[469])|(11))/((0?[1-9])|([12]\d)|(30))|((0?[13578])|(1[02]))/((0?[1-9])|([12]\d)|(3[01]))|(0?2/(0?[1-9])|([12]\d)))/((19\d{2})|(20\d{2})))\b"

Open in new window

0
 

Author Comment

by:patrickm12981
ID: 39201633
Thank you footech - that worked like a charm
0

Join & Write a Comment

Utilizing an array to gracefully append to a list of EmailAddresses
"Migrate" an SMTP relay receive connector to a new server using info from an old server.
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now