1

I have a array with datetime objects .The array lookks like as follows

$advanceresult= array:68 [▼
      "contact" => array:1 [▶]
      "policyBranch" => ArrayCollection {#38322 ▶}
      "assuranceContact" => ArrayCollection {#38337 ▶}
      "info" => null
      "withSurplusShare" => false
      "withSurpassedSurplusShare" => false
      "withoutPremiumInvoice" => false
      "withoutPremiumInvoiceRange" => array:2 [▼
        "start" => DateTime @1577833200 {#38339 ▶}
        "end" => DateTime @1609369200 {#38346 ▶}
      ]
      "showPoliciesFromArchivedContacts" => false
    ]

The withoutPremiumInvoiceRange key value is a datetime object. My problem is when i encode this array as follows

$advanceresultencode=json_encode($advanceresult);
json_decode($advanceresultencode, true);

and decode it back the datetime objects is looking like as follows

enter code here

"withoutPremiumInvoiceRange" => array:2 [▼
    "start" => array:3 [▼
      "date" => "2020-01-01 00:00:00.000000"
      "timezone_type" => 3
      "timezone" => "Europe/Zurich"
    ]
    "end" => array:3 [▶]
  ]

I need the data to datetime object.Can anyone help me acheiving this.

0

1 Answer 1

0

You can't have the datetime without an extra step. You can change the encode process (more info here: Change output of DateTime in json_encode) but same issue on json_decode.

Here is what you can do on json_decode :

<?php

// Here your json as string
$json = ...;

$jsonDecoded = json_decode($json);

$jsonDecoded['withoutPremiumInvoiceRange']['start'] = DateTime::createFromFormat(
    'Y-m-d H:i:s.u', 
    $jsonDecoded['withoutPremiumInvoiceRange']['start']['date'], 
    new DateTimeZone($jsonDecoded['withoutPremiumInvoiceRange']['start']['timezone'])
);
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.