Umair Malik
Umair Malik

Reputation: 1451

Create DateTime for JSON in PHP

I need to hit an API in PHP Laravel and passing Raw body date in it. It requires DataTime to be sent as required by json show in below format.

"ShippingDateTime": "\/Date(1484085970000-0500)\/",

How can I create date like this in PHP/Laravel where I can get any future date (current date + 1). Currently it's giving error that:

DateTime content '23-01-2021' does not start with '\/Date(' and end with ')\/' as required for JSON.

Upvotes: 1

Views: 823

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270657

It looks like you have a Unix timestamp with milliseconds (the 000) on the end, plus a timezone identifier. You should be able to construct that with the date formatting flags UvO (unix time, milliseconds, timezone)

(These are in my timezone, -06:00)

echo date('UvO');
// 1611339488000-0600

// Surround it with the /Date()/ it requests
// Encode it as JSON wherever is appropriate in your code
echo json_encode('/Date(' . date('UvO') . ')/');
// "\/Date(1611339460000-0600)\/"

Assuming you have your dates in DateTime objects, call their format() method to produce your desired date format.

// create your DateTime as appropriate in your application
$yourdate = new \DateTime();

echo json_encode('/Date(' . $yourdate->format('UvO') . ')/');

// Set it ahead 1 day in the future
$yourdate->modify('+1 day');

Upvotes: 2

Related Questions