title: How do I correctly serialize a PSObject with a DateTime into JSON?
body: <p>Let’s say I have a <code>PSObject</code> with an integer and a date that I want to serialize to JSON and have recipients be able to deserialize it. In JavaScript to do this I get the following JSON:</p>
  
  <pre><code>JSON.stringify({Date: new Date(), Number: 23})
  "{"Date":"2014-09-10T14:11:27.092Z","Number":23}"
  
  JSON.parse(JSON.stringify({Date: new Date(), Number: 23}))
  &gt;&gt; Object {Date: "2014-09-10T14:13:28.950Z", Number: 23}
  </code></pre>
  
  <p>That looks like pretty standard JSON that can be interpreted correctly by JavaScript.</p>
  
  <p>However, it appears that PowerShell's <code>ConvertTo-Json</code> is so inconsistent with <code>DateTime</code> serialization that it can't even convert itself back and forth correctly. To fully illustrate this:</p>
  
  <pre><code>PS C:\dev&gt; $testObj = New-Object -TypeName PSobject -Property @{ Date = Get-Date; Number = 23; }
  PS C:\dev&gt; $testObj
  
  Number Date
  ------ ----
      23 9/10/2014 9:52:14 AM
  
  PS C:\dev\git\strawman&gt; $testObj | ConvertTo-Json
  {
      "Number":  23,
      "Date":  {
                   "value":  "\/Date(1410357134361)\/",
                   "DisplayHint":  2,
                   "DateTime":  "Wednesday, September 10, 2014 9:52:14 AM"
               }
  }
  
  PS C:\dev&gt; $testObj | ConvertTo-Json | ConvertFrom-Json
  
  Number Date
  ------ ----
      23 @{value=9/10/2014 1:52:14 PM; DisplayHint=2; DateTime=Wednesday, September 10, 2014 9:52:14 AM}
  </code></pre>
  
  <p>Not only is the JSON it produces for the date property not valid at all and can't be interpreted correctly by JavaScript, but PowerShell's <code>ConvertFrom-Json</code> can't even interpret it correctly to give it the same looking object back.</p>
  
  <p>Is there any way to correctly serialize a <code>PSObject</code> with a <code>DateTime</code> to valid JSON content that can be correctly deserialized by recipients?</p>