1

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.
Umair Malik
  • 1,403
  • 3
  • 30
  • 59
  • Well thats not a standard date format so you will have to do some manual fiddling to make it look like that – RiggsFolly Jan 22 '21 at 18:10
  • 2
    What format is that? – Felippe Duarte Jan 22 '21 at 18:12
  • @FelippeDuarte I'm also not able to found what format is that and how can I make it in PHP. But in there example documentation they showed \/Date(1484085970000-0500)\/ but as it's a past date so it also give error that date should be of future. – Umair Malik Jan 22 '21 at 18:23
  • Let this be a lesson to everyone that inventing your own date interchange format is a really bad idea. – Sammitch Jan 22 '21 at 21:50

1 Answers1

2

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');
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • Thanks for this, it worked well, but can you help me how I can use this to get next date? Like currently it give current date but I wanted to make two dates like this, current date + 1. current date + 2. – Umair Malik Jan 22 '21 at 18:29
  • 1
    By `current_date`, do you mean _today_'s date, or current relative to that past date you had in your example? Calling a `DateTime` object's `modify()` method can change it ahead 1 or 2 days: https://stackoverflow.com/questions/14460518/php-get-tomorrows-date-from-date/14460546 – Michael Berkowski Jan 22 '21 at 18:31
  • I mean today's date by it. I'll try your update answer, Thank you :) – Umair Malik Jan 22 '21 at 18:37