20

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Renji
  • 391
  • 2
  • 7
  • 20

3 Answers3

30

You can use the ParseExact method:

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

Wednesday, December 24, 2014 2:22:57 AM
mjolinor
  • 66,130
  • 7
  • 114
  • 135
  • 12
    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. – Ansgar Wiechers Jan 02 '15 at 13:00
  • 1
    I usually just add the 'tt' specifier to the format string if I'm converting a data that uses AM/PM specifiers. – mjolinor Jan 02 '15 at 13:08
  • 2
    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. – mjolinor Jan 02 '15 at 13:34
  • 2
    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 Jan 19 '16 at 00:10
  • @miracle173 That's weird; `[DateTime]::ParseExact('24/12/2014','dd/MM/yyyy',$null)` works just fine for me. – Franklin Yu Apr 17 '18 at 22:01
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)
AdamL
  • 12,421
  • 5
  • 50
  • 74
5

get-date 24122014022257

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