Solved

Isolate Date in string

Posted on 2013-05-24
10
433 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 30

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 30

Expert Comment

by:Randy Downs
ID: 39196097
Does it find any of the dates?
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 

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 30

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 85

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 40

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 40

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

Featured Post

Want Experts Exchange at your fingertips?

With Experts Exchange’s latest app release, you can now experience our most recent features, updates, and the same community interface while on-the-go. Download our latest app release at the Android or Apple stores today!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Always backup Domain, SYSVOL etc.using processes according to Microsoft Best Practices. This is meant as a disaster recovery process for small environments that did not implement backup processes and did not run a secondary domain controller that ne…
Did you know that more than 4 billion data records have been recorded as lost or stolen since 2013? It was a staggering number brought to our attention during last week’s ManageEngine webinar, where attendees received a comprehensive look at the ma…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

627 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