Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Isolate Date in string

Posted on 2013-05-24
10
Medium Priority
?
440 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 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
Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

 

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 41

Accepted Solution

by:
footech earned 2000 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 41

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

A bad practice commonly found during an account life cycle is to set its password to an initial, insecure password. The Password Reset Tool was developed to make the password reset process easier and more secure.
It’s time for spooky stories and consuming way too much sugar, including the many treats we’ve whipped for you in the world of tech. Check it out!
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)
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
Suggested Courses

972 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