21

I am trying to convert the time stamp value of a file to date time for comparing two date time differences.

The data would be coming in format 24122014_022257. I need to convert this into date time so that I can compare the values:

$usdate="24122014_022257"   
$dateParts = $usdate -split "_"   
$final = $dateparts[0] + $dateParts[1]   

How can I do it?

3 Answers 3

32

You can use the ParseExact method:

[datetime]::ParseExact('24122014_022257','ddMMyyyy_HHmmss',$null)

Wednesday, December 24, 2014 2:22:57 AM
Sign up to request clarification or add additional context in comments.

5 Comments

Use [Globalization.CultureInfo]::InvariantCulture rather than $null. The latter will raise an error if for instance the format string has an AM/PM designator while your system's regional settings don't.
I usually just add the 'tt' specifier to the format string if I'm converting a data that uses AM/PM specifiers.
I don't see the point in adding an option to handle cultural differences in AM/PM designators doing a ParseExact on strings that don't have that designator.
On my system ` [datetime]::ParseExact('24/12/2014','dd/MM/yyyy',$null)` raises an exception but [datetime]::ParseExact('24/12/2014','dd/MM/yyyy',[Globalization.CultureInfo]::InvariantCulture) works fine.
@miracle173 That's weird; [DateTime]::ParseExact('24/12/2014','dd/MM/yyyy',$null) works just fine for me.
10

ParseExact will do just that. You can specify custom datetime format in second parameter. You can leave third parameter as null, or specify a culture to use (it may matter if you're importing files that were generated from system with different time zone).

$usdate="24122014_022257"
[datetime]::ParseExact($usdate,"ddMMyyyy_HHmmss", [System.Globalization.CultureInfo]::CurrentCulture)

Comments

5

get-date 24122014022257

Wednesday, December 24, 2014 2:22:57 AM

1 Comment

For me this returns: 28 January 0001 22:03:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.