Solved

Isolate Date in string

Posted on 2013-05-24
10
430 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
Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

 

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 84

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

Is Your AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

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

Suggested Solutions

In threads here at EE, each comment has a unique Identifier (ID). It is easy to get the full path for an ID via the right-click context menu. However, we often want to post a short link within a thread rather than the full link. This article shows a…
In previous parts of this Nano Server deployment series, we learned how to create, deploy and configure Nano Server as a Hyper-V host. In this part, we will look for a clustering option. We will create a Hyper-V cluster of 3 Nano Server host nodes w…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This video shows how to use Hyena, from SystemTools Software, to update 100 user accounts from an external text file. View in 1080p for best video quality.

710 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