JSON date format problem

This topic contains 3 replies, has 3 voices, and was last updated by  Stig Sörnsen 2 years, 4 months ago.

  • Author
  • #36245

    Stig Sörnsen

    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..

    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:
    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

  • #36251

    Dave Wyatt

    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

  • #36263

    Bob McCoy

    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
  • #36280

    Stig Sörnsen

    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..

You must be logged in to reply to this topic.