Author Posts

March 8, 2016 at 5:44 am

I have a problem in my C# Web API, where an action is return an object with DateTime property. However, when receiving it and converting it to PS object with ConvertFrom-Json the DateTime property is converted to a string.

I then began testing a bit and found it curious how JSON serialize DateTime in Powershell:


$object = New-Object psobject -Property @{ DateTime = (Get-Date) }
$object | ConvertTo-Json | ConvertFrom-Json | gm

This gives me:
DateTime NoteProperty System.Management.Automation.PSCustomObject DateTime=@{value=08-03-2016 13:36:27; DisplayHint=2; DateTime=8. marts 2016 14:36:27}
Too much..

(Get-Date).Date
Gives me:
DateTime NoteProperty datetime DateTime=07-03-2016 23:00:00
Hurray! datetime property, however this is just the Date..

I thought I would be genius just to do this then:
(Get-Date).DateTime
But that gives me a string again...
DateTime NoteProperty string DateTime=8. marts 2016 14:38:37

I could ofcourse do this then:
Get-Date($object | ConvertTo-Json | ConvertFrom-Json).Datetime
I get what I want:
TypeName: System.DateTime

But why oh why?

Any thoughts?

Best regards
Stig

March 8, 2016 at 6:10 am

I'd call this a bug in ConvertTo-Json. It should be treating DateTime as a primitive type and not appending any of the extra ETS properties. (The same can be said for any other primitive type that JSON supports, but as far as I know, none of the other ones have extra properties tacked on by PowerShell's type system).

You can report the bug over on UserVoice: https://windowsserver.uservoice.com/forums/301869-powershell/category/148044-powershell-engine

March 8, 2016 at 6:58 am

I guess I don't understand the value added by creating a new object of an object. Does this get you what you were expecting?

$object = Get-Date

March 8, 2016 at 10:58 am

Bob, no sorry.
I was just trying to simulate getting back a class with a DateTime property – just like from my Web API.

Maybe this is more a C# question?


public HttpResponseMessage Testing()
{
Test test = new Test();
test.TestDate = DateTime.Now;
return Request.CreateResponse(HttpStatusCode.OK, test);
}

public class Test
{
public DateTime TestDate { get; set; }
}

In PS:

Invoke-RestMethod $url -Method Get | gm

What I get return:

TypeName: System.Management.Automation.PSCustomObject

Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
TestDate NoteProperty string TestDate=2016-03-08T19:52:45.2883004+01:00

I would have thought that TestDate would be a DateTime and not string..