Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

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.
question from:https://stackoverflow.com/questions/65850476/create-datetime-for-json-in-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...