2

A script is parsing values from a *.csv file. One of the values is a timestamp in the format 7/21/2018 7:07 AM UTC

This line used to work before:

$DR.Item($property.Name) = (
 [System.DateTime](Get-Date($property.value -replace " UTC", ""))
).TolocalTime() -f "MM/d/yyyy HH:mm:ss"

It is not working anymore. I get the following error:

Get-Date : Cannot bind parameter 'Date'. Cannot convert value "7/21/2018 7:07 AM" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."

2
  • 1
    Try this: ([System.DateTime](Get-Date($($property.value) -replace " UTC", ""))).Tolocaltime() -f "MM/d/yyyy HH:mm:ss" Commented Oct 8, 2018 at 1:41
  • @uSlackr: Wrapping $property.value in $(...) not only makes no difference here, it adds unnecessary overhead. Commented Oct 8, 2018 at 22:53

1 Answer 1

3

Your command failing suggests that the current culture ([cultureinfo]::CurrentCulture) at the time of execution is something other than en-US (US-English), in which case Get-Date won't recognize a date/time string such as "7/21/2018 7:07 AM[1].

The solution is to use a [datetime] cast directly, without involving Get-Date, because a [datetime]cast always uses the invariant culture, which is like the en-US culture with respect to date/time formats:

$DR.Item($property.Name) = ([datetime] ($property.value -replace ' UTC$')) -f "MM/d/yyyy HH:mm:ss"

Caveat: Your call to .ToLocalTime() is not needed for output formatting, as the [datetime] instance you receive will behave as if it were in local time by default, even though it technically is time-zone-agnostic, as reflected in its .Kind property containing Unspecified. That is, your output will reflect the UTC date and time, without indicating so.
If you truly want to translate the input UTC timestamp into the equivalent local time, more work is needed:

$dtUtc = [datetime]::SpecifyKind(($property.value -replace ' UTC$'), 'Utc')
$DR.Item($property.Name) = $dtUtc.ToLocalTime() -f "MM/d/yyyy HH:mm:ss"

[1] PowerShell generally uses the invariant culture when it comes to from-string and to-string type conversions, but, curiously, doesn't do so when passing strings as arguments to compiled cmdlets, as opposed to [advanced] functions (written in PowerShell). This is a known problem, but it may not get fixed for reasons of backward compatibility.

Sign up to request clarification or add additional context in comments.

Comments

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.